我无法在验证中调用我的关联生成的方法。
我的代码非常简单:
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 :(得分:3)
非常确定您需要将lambda传递给in
才能访问当前记录:
validates :winner_id, inclusion: {
in: lambda {|match| match.waiting_players.map { |wp| wp.id }}
}