validate_acceptance_of正在运行但如果选中则不会将true保存到db用户列age_valid。
users.controller.rb
class UsersController < ApplicationController
.
.
.
private
def user_params
params.require(:user).permit(:name, :birthdate, :email, :password,
:password_confirmation, :age_valid)
end
end
_form.html.erb
<%= simple_form_for(@user) do |f| %>
.
.
.
<%= f.input :age_valid,
:as => :boolean,
:label => false,
:inline_label => 'I am 18 years of age or older.' %>
.
.
.
<% end %>
user.rb
class User < ActiveRecord::Base
attr_accessor :remember_token, :age_valid
.
.
.
validates_acceptance_of :age_valid,
:acceptance => true,
:message => "You must verify that you are at least 18 years of age."
这一切都接受它不会将数据库列“age_valid”从false更改为true。我需要这个以保持记录。
这是翻译的DOM
<div class="form-group boolean optional user_age_valid">
<div class="checkbox">
<input value="0" type="hidden" name="user[age_valid]">
<label><input class="boolean optional" type="checkbox" value="1" name="user[age_valid]" id="user_age_valid"> I am 18 years of age or older.</label>
</div>
</div>
使用迁移
class AddAgeValidToUser < ActiveRecord::Migration
def change
add_column :users, :age_valid, :boolean, default: false
end
end
答案 0 :(得分:0)
以下对我有用。
user.rb
class User < ActiveRecord::Base
validates_acceptance_of :age_valid,
:accept => true,
:message => "You must verify that you are at least 18 years of age."
end
new.html.erb
<%= simple_form_for @user, url: {action: "create"} do |f| %>
<%= f.label :name %>
<%= f.text_field :name %>
<%= f.input :age_valid,
:as => :boolean,
:label => false,
:checked_value => true,
:unchecked_value => false,
:inline_label => 'I am 18 years of age or older.' %>
<%= f.submit %>
我删除了属性访问者并将:acceptance => true,
更改为:accept => true
并添加了:checked_value => true,:unchecked_value => false
答案 1 :(得分:0)
您不小心将两种定义验证的语法方法混合在一起。
新语法:
validates :field,
property: {setting: "value"}
旧语法:
validates_property_of :field, setting: "value"
简短的方法 - 从参数中删除acceptance
选项,因为它已在方法名称中说明。
如果你更喜欢新的语法,那就是它的样子:
validates :age_valid, acceptance: {message: "..."}
在这种特定情况下,使用新语法没有任何好处。但是,在其他情况下,它允许您使用多个条件验证属性,而无需重复它们或使用元编程。
在代码可维护性方面,保持一致:选择其中一个,并在项目需要的地方使用它。