Rails 4 - 使用设计创建新用户注册时,复选框协议验证失败

时间:2014-04-30 22:12:58

标签: ruby-on-rails ruby-on-rails-4 devise

我试图加入"接受服务条款"表单上的复选框(称为agreement)。该应用正在使用Devise进行用户管理。

views/devise/registrations/new.html.erb有:

<%= f.check_box :agreement, class: 'form-control' %>

application_controller.rb有:

  def configure_permitted_parameters
    devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(:agreement, :phone, :first_name, :last_name, :domain, :email, :password, :password_confirmation) }
  end

然后在user.rb控制器中,它有

# neither of the below worked
# validates :agreement, :acceptance => true
validates :agreement, acceptance: true

如果我在development.log中查看数据,则会显示agreement字段正确显示的值为1,这是(根据Rails docs的预期值验证):

Parameters: {"utf8"=>"✓", "authenticity_token"=>"jFg6+ZDM1qldh020lv/FQHxlgZkby2dhUbejjXurr4w=", "user"=>{"first_name"=>"Joe", "last_name"=>"Smith", "phone"=>"2098993344", "domain"=>"google.com", "email"=>"test@example.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]", "agreement"=>"1"}, "commit"=>"Create User"} 

但是,无论何时提交表单,它都会显示一条错误消息,即“#34;协议必须被接受&#34;”,是否已经过检查。

关于这是由什么引起的任何想法?

2 个答案:

答案 0 :(得分:7)

尝试使用它进行验证

validates :agreement, acceptance: { accept: true }

根据Rails文档

  

:accept - 指定被视为已接受的值。默认值是字符串“1”,这使得与HTML复选框的关联变得容易。 如果您要验证数据库列,则应设置为true,因为在验证之前该属性从“1”转换为true。

答案 1 :(得分:-1)

我和你一样有同样的场景。这就是我如何完成类似于你想要做的事情:

在routes.rb上:

devise_for :users, :controllers => {:registrations => "registrations"}

创建新控制器 - &gt; RegistrationsController.rb

class RegistrationsController < Devise::RegistrationsController

  def create
      if params[:agree] && verify_recaptcha
        super
      else
        build_resource(sign_up_params)
        clean_up_passwords(resource)
        if params[:agree].nil? && !verify_recaptcha
          flash.now[:alert] = "You did not agree and missing captcha"
        elsif params[:agree].nil?
          flash.now[:alert] = "You did not agree"
        elsif !verify_recaptcha
          flash.now[:alert] = "captcha not correct"
        end
        flash.delete :recaptcha_error
        render :new
      end
  end

end

并将代码放在application_controller.rb

before_filter :update_sanitized_params, if: :devise_controller?

#accept additional attribute for user table
  def update_sanitized_params
    devise_parameter_sanitizer.for(:sign_up) {|u| u.permit(...)}
    devise_parameter_sanitizer.for(:account_update) {|u| u.permit(..)}
  end