在我的Rails 4应用程序中,我检查了一个如此独特的约束:
validates :recipient, uniqueness: {
scope: :user,
message: 'You already have a Connection with this user'
}
现在即使它涉及recipient
我想在recipient.email
字段上显示错误消息。
是一种使用validates
语法执行此操作的方法。
更新:这是某种消息线程,一个用户只能与另一个用户拥有一个用户。因此验证。
答案 0 :(得分:0)
不是一个干净的解决方案,但我相信它正在发挥作用。但我不确定。
after_validation do
msg = 'You already have a Connection with this user'
if errors.messages[:recipient] && errors.messages[:recipient].include? msg
errors.messages[:recipient].reject!{ |i| i == msg }
errors.messages[:recipient][:email] = msg
end
end
答案 1 :(得分:0)
通常我的解决方案我已经工作正常并且会显示验证消息,但是我没有recipient
的明确字段,而是包含recipient
数据的子表单。
就像Arthur指出的那样,我可能需要使用自定义验证器。我现在就开始工作了:
validate :unique_recipient
def unique_recipient
if user.threads.map(&:recipient).map(&:email).include?(recipient.email)
recipient.errors.add(:email, "You already have a connection with #{recipient.first_name}")
end
end
现在检查有点hacky,我喜欢原始解决方案的简单性,但这种方法的好处是我还可以在验证消息中显示用户first_name
。