Ruby On Rails f.checkbox hidden field - ruby-on-rails

I have a check box on a rails form like this:
.columns.small-1
= f.label :private
= f.check_box :private
if the box is unchecked, the form sends correctly with one value passed. If the box is checked the form sends the same field twice with one value as 0 and one as 1, which is causing the box to always show as unchecked" and have a value of 0. Been researching hidden fields in rails but not sure how to apply to this problem.

This is a normal behavior. By default, f.check_box renders a hidden field with value 0. Right after that hidden field, it renders an input field of type "checkbox" with the value 1. The input field and hidden fields have the same name. When both of these values are sent to the server, the later value (checkbox) will overwrite a param value with that name. This should be done automatically for you, unless you are trying to parse the params manually.

Related

check_box_tag doesn't pass any parameter if not checked

I'm trying to have an if else statement in the controller to do something if the check_box_tag is checked and something else if it isn't checked.
<%= check_box_tag "apply[]", 1, false %>
If it is checked and the form is submitted "apply"=>["1"] is passed as a parameter, if it isn't checked nothing is sent.
Can I have a "apply"=>["0"] passed as a param if it isn't checked?
The check_box_tag indeed does not use the hidden field so it does not send anything in case the box is unchecked (unlike the check_box helper, which is nevertheless still not useful in case of an array param, as Meier notes above).
If you are trying to use your checkbox in a similar way as in this SO question (i.e. to send a user-selected array of ids for example), the simple solution might be to react on an empty param in the controller. Something in the way of:
params[:apply] ||= []
If, on the other hand, you wanted to use the checkboxes as an ordered array where each value would be determined by its constant position in the array, either true or false, (i.e. if you wanted to get something like this in the apply param: [0, 1, 0, 0, 1]), this wouldn't work. You'd have to choose a different approach, e.g. use the checkboxes with a hash param instead of array.
The rails guide has a warning box about this special case:
http://guides.rubyonrails.org/form_helpers.html
Array parameters do not play well with the check_box helper. According
to the HTML specification unchecked checkboxes submit no value.
However it is often convenient for a checkbox to always submit a
value. The check_box helper fakes this by creating an auxiliary hidden
input with the same name. If the checkbox is unchecked only the hidden
input is submitted and if it is checked then both are submitted but
the value submitted by the checkbox takes precedence. When working
with array parameters this duplicate submission will confuse Rails
since duplicate input names are how it decides when to start a new
array element. It is preferable to either use check_box_tag or to use
hashes instead of arrays.

Rails can placeholder text be submitted?

Can't find an answer anywhere in Docs... is there a way to make it so that the placeholder value for a number_field_tag or whatever is the value that is submitted to the value if the user doesn't enter anything else?
I.e., in my code below:
<%= number_field_tag "transaction[][#{thing}]", :quantity, min: 0, placeholder: #transactionparams ? #transactionparams["#{thing}"] : 0 %>
I would like the equation in placeholder to evaluate and then be POSTed if the user doesn't enter anything else.
Thanks!
HTML
The issue is HTML, not Rails
The problem is a placeholder is only there to give text that's visible only when the input has no value:
The placeholder attribute specifies a short hint that describes the
expected value of an input field (e.g. a sample value or a short
description of the expected format).
The short hint is displayed in the input field before the user enters
a value.
This attribute (placeholder) does not store any data in the input, meaning when you submit the form, it's not going to send anything to your backend. To fix this, you should should switch from using the placeholder to value attribute:
<%= number_field_tag "transaction[][#{thing}]", :quantity, min: 0, value: #transactionparams ? #transactionparams["#{thing}"] : 0 %>
No.
They will also automatically exclude the placeholder from being sent when the form is submitted.
You'll have to write some JavaScript to set the input's value property using its placeholder attribute, if its value is empty when the form is submitted.

Duplicate hash key in request when posting a form with a checkbox using rails

I have a checkbox iagree and when I am submitting the form I am getting
obj[iagree] : 0
obj[iagree] : 1
in the request. I don't know why is this?
This is expected when using form helpers like check_box_tag.
This helper create a hidden field just before the check box with the same name and the value 0.
The reason for this hidden field is to solve the issue, that the browser sends no parameter at all when a check box is unchecked.
So it is not possible to destingish, whether there is no check box in the form or the check box is uncheced.
With this workaround an unchecked check box is returned with value 0 and a checked checkbox with value 1.
The second parameter just overwrites the hidden field, if checked.
In your params[] you will always see obj[iagree] with either 0 or 1.

selecting checkbox value in ruby on rails

I have some 5 static checkboxes in my html page.
And i want to get the values of a selected checkbox when i click on submit button.
Below is my code snippet,please correct me where am wrong.
for i in 101..105
if (params[":Prod"+i] == 'selected')
#userid=session[:userid].to_i
#prodid="Prod"+i.to_i
#prodname=params[":ProdName"+i].to_s
#price=params[":Price"+i].to_i
#qty=params[":qty"+i].to_i
#Products=Product.create :UserId =>#userid, :ProductId =>#prodid, :ProductName =>#prodname, :Price =>#price,:Quantity =>#qty
if #Products.save
redirect_to viewcart_path
else
render products_path
end
end
Note:My checkboxes id's are Prod101,Prod102,Prod103,Prod104 and Prod105 which i have defined static in my html page.
You can create dynamic hash keys similar to what you're trying, but the syntax is a little off. Use:
params[:"Prod#{i}"]
or
params["Prod#{i}".to_sym]
Note that the value is not "selected" unless you've set that yourself in the view. Depending on whether or not you're using helpers to create the checkboxes, and which helpers/gems you might be using, the values can vary. It's likely you'll get "1" for checked boxes if you haven't overridden it. You might get "0" for unchecked boxes, but by default browsers don't send anything for unchecked boxes, so the param might not be there at all. Some of the form helpers trick the browser into sending "0" by using hidden form fields. Also note that "0" is a true value in Ruby, so you should explicitly check for "1" or whatever checked value you've provided in the form. Check your logs and see what the form submits to be sure.

in rails, What is the value returned in for a checkbox?

I want to set a cookie to expire in 1 year if the 'remember me' checkbox is checked.
I have a checkbox form input like:
<%= check_box_tag 'remember', '', false, :class => 'checkbox' %>
What will the value be when it gets posted?
Will it be true/false or checked or 1 or? I set the value to '' in the helper.
Checkbox will return either 0 or 1.
Don't compare with false and true, as this may cause you problems, since 0 is true in Ruby.
In the rails API documentation it has this helpful explanation of missing parameters and the hidden field work-around:
http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i-check_box
check_box(object_name, method, options = {}, checked_value = "1", unchecked_value = "0")
Returns a checkbox tag tailored for accessing a specified attribute (identified by method) on an object assigned to the template (identified by object). This object must be an instance object (#object) and not a local object. It’s intended that method returns an integer and if that integer is above zero, then the checkbox is checked. Additional options on the input tag can be passed as a hash with options. The checked_value defaults to 1 while the default unchecked_value is set to 0 which is convenient for boolean values.
Gotcha
The HTML specification says unchecked check boxes are not successful, and thus web browsers do not send them. Unfortunately this introduces a gotcha: if an Invoice model has a paid flag, and in the form that edits a paid invoice the user unchecks its check box, no paid parameter is sent. So, any mass-assignment idiom like
#invoice.update_attributes(params[:invoice])
wouldn’t update the flag.
To prevent this the helper generates an auxiliary hidden field before the very check box. The hidden field has the same name and its attributes mimic an unchecked check box.
This way, the client either sends only the hidden field (representing the check box is unchecked), or both fields. Since the HTML specification says key/value pairs have to be sent in the same order they appear in the form, and parameters extraction gets the last occurrence of any repeated key in the query string, that works for ordinary forms.
You get in your action the params
params['remember']
If if check you have the params with false like value. If it's not check you have no params send to your action.

Resources