2012-02-01 27 views
2

我在调用由我的验证中的关联生成的方法时遇到了问题。无法调用验证中的关联方法

我的代码非常简单:

class Match < ActiveRecord::Base 
    # Associations 
    belongs_to :tournament 

    has_many :match_player_relations 
    has_many :waiting_players, through: :match_player_relations 
    has_many :replays 

    # Validations 
    validates :tournament_id, presence: true 
    validates :winner_id, inclusion: { in: waiting_players.map { |wp| wp.id } } 
end 

我在测试中已经证实,有一个waiting_players方法,它工作正常。但是,当我尝试在我的验证中调用它时,出现以下错误:

/Users/max/.rvm/gems/ruby-1.9.3-p0/gems/activerecord-3.1.3/lib/active_record/base.rb:1088:in `method_missing': undefined local variable or method `waiting_players' for #<Class:0x007fc3b498c9c8> (NameError) 
    from /Users/max/workplace/CloudLeagues/app/models/match.rb:11:in `<class:Match>' 

有没有办法解决这个问题?或者我需要删除验证?

+0

是否与'self.waiting_players'工作? – Baldrick 2012-02-01 19:36:52

+0

不,我得到同样的错误。 – Max 2012-02-01 19:41:45

+0

这可能是不可能的,看着这个问题:http://stackoverflow.com/questions/5034988/rails-3-validates-inclusion-of-when-using-a-find-how-to-proc-or- lambda – Baldrick 2012-02-01 19:41:59

回答

3

敢肯定你需要将拉姆达传递给in访问当前记录:

validates :winner_id, inclusion: { 
    in: lambda {|match| match.waiting_players.map { |wp| wp.id }} 
} 
+0

这几乎是正确的答案。这确实证实了winner_id是一个等待玩家。但是,如果winner_id不存在,则有验证失败的警告。简单地添加'presence:false'不能解决这个问题。有没有解决这个问题的方法? – Max 2012-02-02 00:08:52

+0

谢谢,我想通了。我所需要做的就是在包含散列之后加上::winner_id。 – Max 2012-02-02 00:28:21