gpt4 book ai didi

ruby-on-rails-3 - Rails 3.2 验证 - 多个字段

转载 作者:行者123 更新时间:2023-12-03 00:52:23 25 4
gpt4 key购买 nike

我有一个奖励模型。提名者从下拉列表中选择自己,然后从另一个下拉列表中选择提名者。

如何通过模型中的验证来禁止 self 提名?换句话说,提名人不能从提名人选择名单中选择自己。

class Award < ActiveRecord::Base
belongs_to :nominator, :class_name => 'Employee', :foreign_key => 'nominator_id'
belongs_to :nominee, :class_name => 'Employee', :foreign_key => 'nominee_id'
validates :nominator_id, :nominee_id, :award_description, :presence => true
end

提前致谢!

最佳答案

试试这个:

class Award < ActiveRecord::Base  

belongs_to :nominator, :class_name => 'Employee', :foreign_key => 'nominator_id'
belongs_to :nominee, :class_name => 'Employee', :foreign_key => 'nominee_id'

validates :nominator_id, :nominee_id, :award_description, :presence => true
validate :cant_nominate_self

def cant_nominate_self
if nominator_id == nominee_id
errors.add(:nominator_id, "can't nominate your self")
end
end
end

这是自定义验证。有关验证的更多信息,包括执行自定义验证的其他方法,请参阅 Rails Guides .

关于ruby-on-rails-3 - Rails 3.2 验证 - 多个字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16656644/

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