Custom Association Method - Can This Be Done

前端 未结 2 508
执笔经年
执笔经年 2021-01-06 04:15

I have three models: Wager, Race, RaceCard and WagerType. I\'ve created a has_many association in Wagers and have added a custom association method (in_wager). The purpose

2条回答
  •  天命终不由人
    2021-01-06 04:53

    you can use self.proxy_association.owner to get the parent object inside of an association method. From there you can get the values you want.

    If I understand your models correctly then the code should look something like this.

    class Wager < ActiveRecord::Base
    belongs_to :wager_type
    belongs_to :race_card
      has_many :races, :through => :race_card do
        def in_wager
          owner = self.proxy_association.owner
          b = owner.race_nbr
          a = b - owner.wager_type.legs + 1
          where('races.race_nbr BETWEEN ? AND ?', a, b)
        end
      end
    end
    

    The I got this from the Rails api reference to Association Extensions (The reference to proxy_association is at the bottom of the section).

提交回复
热议问题