ruby-on-railsvalidation

How do I set a Rails validation to ensure that two attributes can't have the same value?


I have a form on my site that lets users direct a message at other users, but I want to ensure that they can't direct a message at themselves.

The class has attributes :username and :target_user, and I just want to set a validation that checks to make sure that these attributes can't have the same value, before anything gets saved.

I figured it would look something like this:

validates_presence_of :user_id, :username, :target_user, :message, :tag

validate :username != :target_user

But clearly don't know enough Ruby to do it correctly.


Solution

  • Up at the top with your validations:

    validate :username_does_not_equal_target
    

    and then a private/protected method within your model code:

    def username_does_not_equal_target
      @errors.add(:base, "The username should not be the same as the target user") if self.username == self.target_user
    end
    

    OR to attach the error to a specific attribute:

    def username_does_not_equal_target
      @errors.add(:username, "should not be the same as the target user") if self.username == self.target_user
    end
    

    You can change the text of your error message or the name of your method.

    to read more on errors: http://api.rubyonrails.org/classes/ActiveRecord/Errors.html to read more on validations: http://api.rubyonrails.org/classes/ActiveRecord/Validations/ClassMethods.html