使用attr_accessor进行验证始终会返回错误

时间:2017-03-19 10:24:28

标签: ruby-on-rails ruby-on-rails-3

我正在尝试验证不属于User

的2个字段
attr_accessor :terms_of_service, :privacy_policy

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

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

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

但是,出于某种原因 - 无论参数是真还是不存在/ 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

2 个答案:

答案 0 :(得分:1)

问题是我没有正确消毒我的参数

这就是我在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

答案 1 :(得分:0)

您需要使用自定义验证程序。 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}"