gpt4 book ai didi

ruby-on-rails - 无法从验证中调用关联方法

转载 作者:行者123 更新时间:2023-12-04 05:59:25 25 4
gpt4 key购买 nike

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

我的代码很简单:

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>'

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

最佳答案

很确定您需要将 lambda 传递给 in访问当前记录:

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

关于ruby-on-rails - 无法从验证中调用关联方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9102035/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com