Katie M
Katie M

Reputation: 1131

Rails 3.2 Validation - Multiple Fields

I have an award model. The NOMINATOR selects himself from a dropdown list, then selects the NOMINEE from another dropdown list.

How can I disallow self-nomination via a validation in the model? In other words, the nominator cannot select himself from the nominee selection list.

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

Thanks in advance!

Upvotes: 15

Views: 16381

Answers (1)

Whit Kemmey
Whit Kemmey

Reputation: 2230

Try this:

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

This is a custom validation. More information about validations, including other ways to do custom validations, is available in the Rails Guides.

Upvotes: 34

Related Questions