Chris Wissmach
Chris Wissmach

Reputation: 505

How to check if a check_box in simple_form has been checked

Here's the HTML that it produces

f.check_box :tos

produces

<input name="user[tos]" type="hidden" value="0">

<input id="user_tos" name="user[tos]" type="checkbox" value="1">

What would I need to do in a controller to check if it's been checked?

Upvotes: 0

Views: 855

Answers (2)

ConnorCMcKee
ConnorCMcKee

Reputation: 1645

Assuming you mean you want to find out if it is checked upon submission, then you could get it's value via params[:user][:tos]. All submitted data from a form is stored in the params hash, and its location is equivalent to the name attribute of the input. So for instance:

if params[:user][:tos] == "1"
    # Do whatever is here if checked
else
    # Do whatever is here if unchecked
end

If you need to react to its state of being checked on a web page, this cannot be done by the controller, and must use JavaScript. Something like:

if (document.getElementById('user_tos').checked == 1){
    // Do whatever is here if checked
} else {
    // Do whatever is here if unchecked
}

Addendum

When receiving a parameter via your controller, don't use that value to create a new object (i.e. Thing.create( thing_value: params[:user][:tos] )). If this is y our goal, you should look into "strong parameters," and how Rails implements them.

Addendum 2

Thanks to ruby's duck typing (dynamic typing) and the nature of the params Hash, url encoding, etc. Integers sent via params, in this case params[:user][:tos], will get mutated to String. So you'll need to check for "1" (the string form) not 1 (the int form).

Upvotes: 1

Martin M
Martin M

Reputation: 8638

In th controller, all parameters are delivered in the hash params. Your params will have a key user with the hash of all user input fields.

The hidden field, that simple_form insterts before the checkbox ensures that params[:user][:tos] is set (with value 0) even when the checkbox is not set.

So you can check

if params[:user][:tos]>0
  # your stuff
end

Upvotes: 0

Related Questions