Rails 验证一个值不等于另一个值

发布于 2025-01-08 13:20:22 字数 70 浏览 3 评论 0原文

有没有一种方法可以在保存记录之前验证一个文本字段不等于另一个文本字段?我有两个带有整数的文本字段,它们不能相同才能使记录有效。

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

心凉 2025-01-15 13:20:22

您可以添加自定义验证:

class Something
  validate :fields_a_and_b_are_different

  def fields_a_and_b_are_different
    if self.a == self.b
      errors.add(:a, 'must be different to b')
      errors.add(:b, 'must be different to a')
    end
  end

每次验证对象时都会调用该验证(无论是显式验证还是在保存验证时),并向两个字段添加错误。您可能希望两个字段都出现错误,以便在表单中以不同的方式呈现它们。

否则你可以添加一个基本错误:

errors.add(:base, 'a must be different to b')

You can add a custom validation:

class Something
  validate :fields_a_and_b_are_different

  def fields_a_and_b_are_different
    if self.a == self.b
      errors.add(:a, 'must be different to b')
      errors.add(:b, 'must be different to a')
    end
  end

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:

errors.add(:base, 'a must be different to b')
多像笑话 2025-01-15 13:20:22

在你的模型中:

validate :text_fields_are_not_equal

def text_fields_are_not_equal
  self.errors.add(:base, 'Text_field1 and text_field2 cannot be equal.') if self.text_field1 == self.text_field2
end

In your model:

validate :text_fields_are_not_equal

def text_fields_are_not_equal
  self.errors.add(:base, 'Text_field1 and text_field2 cannot be equal.') if self.text_field1 == self.text_field2
end
心碎的声音 2025-01-15 13:20:22

更有趣:

  validates :a, exclusion: { in: ->(thing) { [thing.b] } }

虽然这当然不是很可读,但它很优雅 - 我们利用过程的排除验证来防止值相等。有些人可能更喜欢更详细的方法,但我喜欢简洁——不存在的代码不会有错误。另外,这将获取默认 Rails 位置的错误消息,这对于 i18n 目的可能很方便。

(更好?)

more fun:

  validates :a, exclusion: { in: ->(thing) { [thing.b] } }

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?)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文