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.
Up at the top with your validations:
and then a private/protected method within your model code:
OR to attach the error to a specific attribute:
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
I hope this helps, happy coding!