开发者

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.


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

I hope this helps, happy coding!


Use validate

def validate
  if self.username == self.target_user
    self.errors.add :base, "You can't send message to yourself."
  end
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜