Search code examples
ruby-on-railssimple-form

validates_acceptance_of working but not saving true user:age_valid in database


The validate_acceptance_of is working but it is not saving the true to the db user column age_valid if checked.

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."

This all works accept it does not change the database column "age_valid" from false to true. I need this to happen for record keeping.

Here is the translated 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>

Migration used

class AddAgeValidToUser < ActiveRecord::Migration
 def change
   add_column :users, :age_valid, :boolean, default: false
end
end

Solution

  • The below works for me.

    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 %>
    

    I removed attribute accessor and changed :acceptance => true, to :accept => true and added :checked_value => true,:unchecked_value => false