我有一个带有一些嵌套字段的注册表单,并且在此表单中,我添加了一个用于服务条款的复选框。
我正在尝试验证复选框是否已选中,如果未选中则返回错误。
validates_acceptance_of :agreement, :allow_nil => true, :accept => true, :on => :create
我的帐户表中确实有一个设置为默认值的 bool 列。
add_column :accounts, :agreement, :boolean, default: false
另外,我已将
:agreement
添加到允许的 Controller 参数中。形式如下:
<%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>
<div class="centerList">
<div id="error_explanation">
<%= devise_error_messages! %></div>
</div>
<div class="form-group">
<span class="asterisk_input"></span>
<%= f.email_field :email, autofocus: true, placeholder: "email", :class=>"form-control" %>
</div>
<div class="form-group">
<span class="asterisk_input"></span>
<%= f.password_field :password, placeholder: "password", autocomplete: "off", :class=>"form-control" %>
</div>
<div class="form-group">
<span class="asterisk_input"></span>
<%= f.password_field :password_confirmation, placeholder: "confirm password", autocomplete: "off", :class=>"form-control" %>
</div>
<%= f.fields_for :account do |form| %>
<div class="form-group">
<span class="asterisk_input"></span>
<%= form.text_field :street, placeholder: "street", :class=>"form-control" %>
</div>
<div class="form-group">
<span class="asterisk_input"></span>
<%= form.text_field :city, placeholder: "city", :class=>"form-control" %>
</div>
<div class="form-group">
<span class="asterisk_input"></span>
<%= form.text_field :state, placeholder: "state", :class=>"form-control" %>
</div>
<div class="form-group">
<span class="asterisk_input"></span>
<%= form.text_field :zip_code, placeholder: "zip code", :class=>"form-control" %>
</div>
<div class="form-group">
<span class="asterisk_input"></span>
<%= form.country_select :country, ["US"], {}, { :class => "form-control", :id=>"sign-frm-input" } %>
</div>
<div class="form-group">
<%= form.check_box :agreement %> I agree to the <%= link_to 'Terms', term_path(:id=>1) %>.
</div>
<% end %>
<div class="form-group">
<%= f.submit "Sign up", :class=>'btn btn-primary' %>
<% end %>
但是,即使我接受,它也会返回形式错误
agreement must be accepted
。任何想法我可能会错过的地方! 最佳答案
尝试:validates :agreement, acceptance: {accept: true} , on: :create,allow_nil: false
如果您正在接受验收,则不想使用:allow_nil => true
。
关于ruby-on-rails - Rails 5 : validation of acceptance for a checkbox,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48522946/