I have three models: Wager, Race, RaceCard and WagerType. I created a has_many association in Wagers and added a custom association method (in_wager). The purpose of this method is to filter out the correct races for each bet. (Some bets cover several races). I would like to be able to do something like: Wager.first.races.in_wager and return the corresponding races.
class Wager < ActiveRecord::Base belongs_to :wager_type belongs_to :race_card has_many :races, :through => :race_card do def in_wager where('races.race_nbr BETWEEN ? AND ?', a, b) end end end
My custom method works fine if I hardcode the values ββfor a and b, however I need these values ββto be dynamic. In particular, the value of b must be equal to the race_nbr attribute from the Wager model:
b = wagers.race_nbr
and the value of a should be equal to b minus the number of races for a certain type of bet (known as legs) plus 1:
a = b - Legs + 1
The leg value is in the WagerType model. Note that Wagers are owned by WagerType and WagerType has_many Wagers. Therefore, a can be expressed as:
a = (b - (select wager_types.legs where wagers_types.id = wagers.wager_type_id) + 1)
MY question is: is it really possible to do this with my in_wager association method. Iβve been staring at this couple for a couple of days and canβt figure out how to assign the correct values ββa and b. Also, if you feel like I'm wrong, I would be glad to hear alternative approaches. Thank you for your help.
Note. I never mentioned the RaceCard or Races models. They have the following associations:
class RaceCard < ActiveRecord::Base has_many :races end class Races < ActiveRecord::Base belongs_to :race_card has_many :wagers, :through => :race_card end
Update: I read Design Templates in Ruby last night and stumbled upon Proc. I will see if I can use it in the Association method to calculate the values ββfor a and b.