Rails 3.2验证 - 多个字段

时间:2013-05-20 19:10:58

标签: ruby-on-rails-3

我有奖励模特。 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

提前致谢!

1 个答案:

答案 0 :(得分:25)

试试这个:

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