Custom Association Method - Can This Be Done

前端 未结 2 485
执笔经年
执笔经年 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).

    0 讨论(0)
  • 2021-01-06 04:58

    Do you absolutely need to use an has_many relation ? maybe you could just create a method in the Wager class

    def races
      b = self.race_nbr
      a = b + self.race_card.legs
      Races.find_by_race_card_id(self.id).where('race_nbr BETWEEN ? AND ?', a, b)
    end 
    

    I don't really understand your model, so the request is certainly wrong, but you get the idea...

    0 讨论(0)
提交回复
热议问题