Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 525
Katie M Avatar asked May 20 '13 19:05

Katie M


People also ask

What is the difference between validate and validates in rails?

So remember folks, validates is for Rails validators (and custom validator classes ending with Validator if that's what you're into), and validate is for your custom validator methods.

How does validation work in Rails?

Rails validation defines valid states for each of your Active Record model classes. They are used to ensure that only valid details are entered into your database. Rails make it easy to add validations to your model classes and allows you to create your own validation methods as well.


1 Answers

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.

like image 181
Whit Kemmey Avatar answered Nov 06 '22 13:11

Whit Kemmey