2

How do i add a boolean true false column to existing database with default value false? (lets say checkbox for user_agreement)

my existing table:

create_table "users", :force => true do |t|
    t.string   "name"
    t.string   "email"
end

what shoud i do after that? should i do something like this?

html:

<%= check_box_tag "user_agreement[]" %>

controller:

if params[:user_agreement] == '1'
    user = User.find_by_id(params[:id])
    user.update_attribute(:user_agreement, true)
    flash[:success] = "accepted agreement"
else
    user = User.find_by_id(params[:id])
    user.update_attribute(:user_agreement, false)
    flash[:success] = "didn't accepted agreement"
end
1

1 Answer 1

5

First you need to run a migration to add the column user_agreement to your User model:

$ rake generate migration AddUserAgreementToUsers user_agreement:boolean

Open up the migration file you just generated and add the default of false:

db/migrate/_add_user_agreement_to_users.rb

class AddUserAgreementToPeople < ActiveRecord::Migration
  def change
    add_column :people, :user_agreement, :boolean, default: false
  end
end

Run the migration to make the changes to the database:

$ rake db:migrate

app/controllers/users_controller.rb

If you're running Rails 4 you'll need to add user_agreement to the list of parameters you'll accept:

private

  def user_params
    params.require(:user).permit(:name, :email, :user_agreement)
  end

And finally add user_agreement to your form.

app/views/users/_form.html.erb

<%= form_for @user %>
  ...
  <%= f.check_box :user_agreement %>
  ...
<% end %>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.