2012-02-01 29 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