如何设置Rails验证以确保两个属性不能具有相同的值?

kat*_*ray 2 validation ruby-on-rails

我的网站上有一个表单,允许用户在其他用户处发送消息,但我想确保他们不能自己定向消息.

该类具有属性:username和:target_user,我只想设置一个验证,检查以确保在保存任何内容之前这些属性不能具有相同的值.

我认为它看起来像这样:

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

validate :username != :target_user
Run Code Online (Sandbox Code Playgroud)

但显然不知道Ruby能够正确地做到这一点.

Geo*_*tte 5

在您的验证顶部:

validate :username_does_not_equal_target
Run Code Online (Sandbox Code Playgroud)

然后在模型代码中使用私有/受保护的方法:

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
Run Code Online (Sandbox Code Playgroud)

或者将错误附加到特定属性:

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
Run Code Online (Sandbox Code Playgroud)

您可以更改错误消息的文本或方法的名称.

阅读有关错误的更多信息:http://api.rubyonrails.org/classes/ActiveRecord/Errors.html 阅读有关验证的更多信息:http: //api.rubyonrails.org/classes/ActiveRecord/Validations/ClassMethods.html

我希望这有帮助,编码愉快!