Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 4 - Checkbox and Boolean Field

I have looked at loads of different articles on the web (some on here) about this issue but there are so many different suggestions, lots of which are outdated, that it has led me to ask here today...

I have a field in my Users table called admin? which is a :boolean data type. I also have a checkbox in the form in my view called admin? - I would like to be able to create TRUE and FALSE accordingly in the table record when the form is submitted.

Part of my view code is:

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

Also I have permitted this in my post_params - is this a necessary step?

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

When I submit the form at the moment, the admin? field is unaffected. Any advice would be much appreciated.

like image 552
tommyd456 Avatar asked Sep 08 '13 14:09

tommyd456


2 Answers

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)

like image 55
DickieBoy Avatar answered Oct 20 '22 21:10

DickieBoy


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.

like image 24
SomeDudeSomewhere Avatar answered Oct 20 '22 20:10

SomeDudeSomewhere