如何将动态条件应用于Rails 3 has_many:通过关联

时间:2012-01-15 02:59:57

标签: ruby-on-rails-3 associations

我有三种模式:RaceCards,Races和Wagers。

class RaceCard < ActiveRecord::Base
has_many :races
has_many :wagers
end

class Race < ActiveRecord::Base
belongs_to :race_card
has_many :wagers, :through => :race_card
end

class Wager < ActiveRecord::Base
belongs_to :race_card
has_many :races, :through => :race_card
end

rails g model RaceCard race_card_date:date number_of_race:integer

rails g model Race race_card_id:integer race_nbr:integer

rails g model Wager race_nbr:integer race_card_id:integer wager_type:string payoff:integer

所以,如果我在控制台中这样做:

Wager.first.races  #All races on the race card are returned. Good!

但是我想要一种确定返回比赛的方法,所以我添加一个条件:

if I add this:   :condition =>{:race_nbr => 1}

Wager.first.races  #Return just race 1, but this is static (always set to 1)

我的问题是如何在Wager模型中将条件设置为race_nbr:

:condition => {:race_nbr => wager.race_nbr}  #throws an error
:condition => {:race_nbr => self.race_nbr}   #throws an error

我已经尝试了很多其他的东西,但似乎无法得到它。任何指导将不胜感激。提前谢谢。

更新:我现在尝试了下面的PinnyM建议的解决方案

:condition => "wagers.race_nbr = races.race_nbr" #unfortunately this yields the following:

SQL error or missing database (no such column wagers.race_nbr)

1 个答案:

答案 0 :(得分:1)

您可以使用范围执行此操作:

def Race < ActiveRecord::Base
  scope :for_race_nbr, lambda { |race_nbr| where(:race_nbr => race_nbr) }
end

def Wager < ActiveRecord::Base
  def races_for_race_nbr
    races.for_race_nbr(race_nbr)
  end
end