使用 attr_accessor 进行验证总是 returns 出错

using attr_accessor for validation always returns an error

我正在尝试验证不属于 User table

的 2 个字段
attr_accessor :terms_of_service, :privacy_policy

 validates :terms_of_service, presence: true
 validates :privacy_policy, presence: true

在客户端发送的请求中,:terms_of_service:privacy_policy参数可以不存在,也可以是布尔值。

Rails 仅当值为 true 时才需要通过验证(即仅在参数不存在或为 false 时才发送错误)

但是,出于某种原因 - 无论参数为真还是 absent/false

,验证总是失败

我什至试过了

 validates_presence_of :terms_of_service
 validates_presence_of :privacy_policy

还有

  validates :terms_of_service, acceptance: true
  validates :privacy_policy, acceptance: true

这些是我要发送给 rails

的参数
{"username"=>"justin", "email"=>"justin@justin.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]", "terms_of_service"=>false, "privacy_policy"=>false, "confirm_success_url"=>"http://localhost:4000", "config_name"=>"default", "registration"=>{"username"=>"justin", "email"=>"justin@justin.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]", "terms_of_service"=>false, "privacy_policy"=>false, "confirm_success_url"=>"http://localhost:4000"}}

当我尝试使用

记录以下内容时
puts "terms_of_service : #{:terms_of_service}"

我得到以下输出

terms_of_service : terms_of_service

您需要使用自定义验证器。 presence: true 检查字段是否存在,因此如果将其设置为包括 false 在内的任何值,它将通过。

validate :privacy_policy_valid?

privacy
def privacy_policy?
  errors.add(:privacy_policy "must be true") if privacy_policy
end

对于你的日志语句试试

puts "terms_of_service : #{terms_of_service}"

问题是我没有正确清理我的参数

这就是我在 applicationController.rb

中所做的
before_action :configure_permitted_parameters, if: :devise_controller?


def configure_permitted_parameters
    devise_parameter_sanitizer.permit(:sign_up, keys: [:username,:terms_of_service,:privacy_policy])
  end