【问题标题】:Rails Validate Field is True, If PresentRails 验证字段为真,如果存在
【发布时间】:2017-11-23 20:04:55
【问题描述】:

我发现了很多关于如何验证字段是否存在的帖子,如果另一个条件为真,例如:

Rails: How to validate format only if value is present?

Rails - Validation :if one condition is true

但是,我该如何反其道而行之呢?

我的用户有一个名为terms_of_service 的属性。

如何最好地编写一个验证来检查terms_of_service == true(如果存在)?

【问题讨论】:

  • terms_of_service 的数据类型是什么? boolean?
  • 是的,它是一个布尔值。
  • 要检查它的true 还是验证它应该是true
  • 我想在提交表单时检查该值是否为真(他们同意条款)。
  • 如果它不是真的添加错误,对吧?

标签: ruby-on-rails


【解决方案1】:

您正在寻找acceptance validation

你可以像这样使用它:

class Person < ApplicationRecord
  validates :terms_of_service, acceptance: true
end

或者有更多的选项,像这样:

class Person < ApplicationRecord
  validates :terms_of_service, acceptance: { message: 'must be abided' }
end

[编辑]

您也可以将您希望该字段的选项设置为单个项目或数组。因此,如果您将字段存储在隐藏属性中,您可以检查它是否仍然“接受”,但您描述接受:

class Person < ApplicationRecord
  validates :terms_of_service, acceptance: { accept: ['yes', 'TRUE'] }
end

【讨论】:

  • 我认为这通常可以工作,但该字段将被隐藏(不是复选框)。
  • 更新了我的答案,包括设置字段期望的方式。这样,如果它被存储在一个隐藏的属性中,你可以选择你想要被“接受”的答案。
【解决方案2】:

我想不出任何可以满足您目的的默认验证方法,但您可以使用 自定义验证。此外,boolean 可以是真或假,所以你只需要检查它是否。像这样的东西应该可以工作。

validate :terms_of_service_value

def terms_of_service_value
  if terms_of_service != true
    errors.add(:terms_of_service, "Should be selected/True")
  end
end

【讨论】:

    猜你喜欢
    • 2017-07-18
    • 2020-08-03
    • 2019-05-15
    • 2020-04-28
    • 2022-07-14
    • 2023-03-04
    • 2020-12-23
    • 2020-06-13
    相关资源
    最近更新 更多