views:

41

answers:

2

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.

+1  A: 

Use validate

def validate
  if self.username == self.target_user
    self.errors.add :base, "You can't send message to yourself."
  end
end
Salil
I don't recommend monkey patching the validate method. I would rather to call to a method symbol than redefine validate, this allows you to have more than just the one validation.
Geoff Lanotte
I second Geoff's comment .
NM
+2  A: 

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_to_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

I hope this helps, happy coding!

Geoff Lanotte
Thanks, worked perfectly
kateray