14

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

如何通过模型中的验证来禁止自我提名?换言之,提名人不能从被提名人选择列表中选择自己。

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

提前致谢!

4

1 回答 1

30

尝试这个:

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 指南中提供了有关验证的更多信息,包括进行自定义验证的其他方法。

于 2013-05-20T19:23:33.847 回答