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!
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With