Rails 4 - Checkbox and Boolean Field

No need to name it ":admin?"

Just use this in your form:

Admin User&#63; <%= f.check_box :admin %>

And the permitted params like this:

params.require(:staff).permit(:name, :email, :password, :password_confirmation, :admin)

That should work.


For anyone that has a form that isn't part of an object.

I found using checkbox syntax like:

= check_box 'do_this', '', {}, 'true', 'false'

Then in the controller side:

ActiveRecord::ConnectionAdapters::Column.value_to_boolean(params[:do_this])

Will give you the correct boolean value of do_this.

Examples:

[1] pry(main)> ActiveRecord::ConnectionAdapters::Column.value_to_boolean("true")
=> true
[2] pry(main)> ActiveRecord::ConnectionAdapters::Column.value_to_boolean("false")
=> false
[3] pry(main)> ActiveRecord::ConnectionAdapters::Column.value_to_boolean("1")
=> true
[4] pry(main)> ActiveRecord::ConnectionAdapters::Column.value_to_boolean("0")
=> false

Edit: The above is deprecated, use:

ActiveRecord::Type::Boolean.new.type_cast_from_database(value)

It gives the same results as the examples above.

Rails 5

The above options don't work in Rails 5. Instead, use the following:

ActiveRecord::Type::Boolean.new.cast(value)