2013-05-20 60 views
9

我有一個獎模型。 NOMINATOR從下拉列表中選擇自己,然後從另一個下拉列表中選擇NOMINEE。Rails 3.2驗證 - 多個字段

如何通過模型中的驗證來禁止自我提名?換句話說,提名人不能從被提名人選擇名單中選擇自己。

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 

在此先感謝!

回答

23

試試這個:

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

+0

這就是我正在建議的 - 自定義驗證方法。有關詳細信息,請參閱http://guides.rubyonrails.org/active_record_validations_callbacks.html#performing-custom-validations。 – MrTheWalrus

+0

不客氣。並感謝@MrTheWalrus對Rails指南的評論;我添加了一個鏈接。 –

+0

.... aaaand鏈接是404. * facepalm * – pjmorse