Rails 验证一个值不等于另一个值
有没有一种方法可以在保存记录之前验证一个文本字段不等于另一个文本字段?我有两个带有整数的文本字段,它们不能相同才能使记录有效。
Is there a way to validate that one text_field does not equal another before saving record? I have two text_fields with integers in them and they cannot be identical for record to be valid.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以添加自定义验证:
每次验证对象时都会调用该验证(无论是显式验证还是在保存验证时),并向两个字段添加错误。您可能希望两个字段都出现错误,以便在表单中以不同的方式呈现它们。
否则你可以添加一个基本错误:
You can add a custom validation:
That will be called every time your object is validated (either explicitly or when you save with validation) and will add an error to both of the fields. You might want an error on both fields to render them differently in the form.
Otherwise you could just add a base error:
在你的模型中:
In your model:
更有趣:
虽然这当然不是很可读,但它很优雅 - 我们利用过程的排除验证来防止值相等。有些人可能更喜欢更详细的方法,但我喜欢简洁——不存在的代码不会有错误。另外,这将获取默认 Rails 位置的错误消息,这对于 i18n 目的可能很方便。
(更好?)
more fun:
Though of course this isn't terribly readable, but it's elegant - we're leveraging the exclusion validation with a proc to prevent the values from being equal. A more verbose approach might be preferred by some, but I'm a fan of brevity - code that doesn't exist can't have bugs. Plus, this will get its error message the default rails location, which may be convenient for i18n purposes.
(better?)