I'm using Rails 3.2. I have a search form that has radio buttons below it. It searches based on which of the radio buttons are selected. Currently I have this in my view:
= radio_button_tag(:ad_type, "free")
= label_tag(:ad_type_free, "free")
= radio_button_tag(:ad_type, "paid")
= label_tag(:ad_type_paid, "paid")
= radio_button_tag(:ad_type, "featured")
= label_tag(:ad_type_featured, "featured")
So my question is this, how do I set the default radio button to be selected? I have tried using radio_button_tag(:ad_type, "free", :checked => true), but after submitting the form, it always selects that radio button. What I want is to select the value based on the previous request. Should I get the value from the url params? If so, how do I set the initial default value(when there are no previous searches)? Thanks a lot.
Update
I've created a helper method ad_type_selected?
def ad_type_selected?(ad_type)
selected_ad_type = params[:ad_type] || "free"
(selected_ad_type == ad_type) ? true : false
end
And I have this in my view:
= radio_button_tag(:ad_type, "free", :checked => ad_type_selected?("free"))
However, the radio button still doesn't get selected. Checking the logs, I see that the first call to the helper returns true, and the others false, which is what I want. But problem is it still doesn't select the radio button. If I check the input tag, I can only see that the checked attribute is set to "checked".
I'm grave digging, but I just came across this.
<label class='checkbox-inline'>
<%= radio_button_tag :option, :user, true %>
Username
</label>
<label class='checkbox-inline'>
<%= radio_button_tag :option, :email, params[:option] == 'email' ? true : false %>
Email
</label>
<label class='checkbox-inline'>
<%= radio_button_tag :option, :name, params[:option] == 'name' ? true : false %>
Full Name
</label>
So... this will set the first button by default (and always), but if the other params are selected they'll become true. Radio buttons will always have the last true button selected for you, so as long as you put your default option first in the list, set to true, and the rest set to:
params[:name_of_your_buttons] == 'button_value' ? true : false
Apparently, adding a checked attribute for all the radio buttons causes the last radio button to be always selected. So what I did is to just add a checked attribute if the params matched the radio button.
So for my example, I just used a helper to generate the appropriate radio button like so:
def ad_type_radio_button(ad_type)
selected_ad_type = params[:ad_type] || "free"
if selected_ad_type == ad_type
radio_button_tag(:ad_type, ad_type, :checked => true)
else
radio_button_tag(:ad_type, ad_type)
end
end
And have this in my view:
= ad_type_radio_button("free")
I know it's far from elegant, but it behaves correctly now.
This snippet will set checked to false if params[:ad_type] is nil. Otherwise, it will set checked to true if params[:ad_type] is set to true.
radio_button_tag(:ad_type, "free", :checked => (params[:ad_type] == nil ? false : params[:ad_type]))
Just in case you haven't seen the shorthand for if / then / else used above, it goes:
test-expression ? if_true_expression : if_false_expression
According to the docs, checked isn't an options hash parameter, it is just a boolean.
This didn't worked (at least in rails 4):
= radio_button_tag(:ad_type, "free", :checked => ad_type_selected?("free"))
It should be:
= radio_button_tag(:ad_type, "free", ad_type_selected?("free"))
Related
I want the checkboxes are checked if the object's boolean attribute is true. Otherwise, it should be unchecked.
<%=check_box_tag user.id, 'check_user', {:checked => user.submit, :disabled => true}%>
submit is an attribute the user has. Thanks for your help
check_box_tag(name, value = "1", checked = false, options = {})
The below code should work
<%= check_box_tag user.id, 'check_user', user.submit, {:disabled => true} %>
As submit is a boolean attribute, its value can be directly passed to the checked to make the checkbox checked or unchecked based on its value.
I made checkboxes using the following rails form helper:
<%= check_box("tag", tag.id) %>
However, I need to make some of them checked by default. The rails documentation doesn't specify how to do this. Is there a way? How?
Here's how to do it as of rails 4, I didn't check older documentation.
<%= check_box("tag", tag.id, {checked: true}) %>
This will make the checkbox checked. Of course instead of true you will put in some logic which determines if each one is checked.
If you need the check_box to be checked on new, and correctly filled on edit you can do:
<%= f.check_box :subscribe, checked: #event.new_record? || f.object.subscribe? %>
As I mentioned here
The rails docs do say how to have it checked and it depends on the object. If you don't have an instance object to use with check_box, then your best option is to use the check_box_tag as mentioned. If you do, read on.
Here's the link to the docs on the check_box helper. Basically how this works is that you have to have an instance variable defined. That instance variable must have a method that returns an integer or a boolean. From the docs:
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.
For example, let's assume you have a #tag instance in your view which has an enabled method. The following snippet would cause the checkbox to be checked when enabled is true on the #tag object and unchecked when it is false. To have it enabled by default, set the enabled attribute to true in your controller. The last two variables are the values that you want to submit with the form when the check box is checked and unchecked.
<%= check_box "tag", "enabled", {}, "1", "0" %>
A lot of times, you'll see the check_box helper used with a form builder. So if form_for was used for the #tag instance, you would more than likely use this snippet:
<%= f.check_box :enabled %>
No need of writing checked: true for rails >= 4.0
Simply write
<%= check_box_tag "name", value, true %> # true or false
The check_box_tag instead of check_box has a way to set that it's been checked.
Using check_box_tag you can set it to true so that it's already checked. More info here: http://api.rubyonrails.org/classes/ActionView/Helpers/FormTagHelper.html#method-i-check_box_tag
This answer is only related to f.check_box
f.check_box can take up to 4 arguments:
input name
hash containing options such as html class, id, etc
which value represents "checked" (defaults to "1")
which value represents "unchecked" (default to "0")
So if your boolean field is stored as either 1 or 0 (default for Rails) then everything is fine and well. Rails will recognize whether the field is checked or not.
However, if you're using a different data storage or a framework which is storing booleans in another format, you need to specify which values correspond to checked and unchecked.
Here's an example:
<%= f.check_box :accept_privacy_policy, { class: 'my-class' }, "true", "false" %>
References
https://api.rubyonrails.org/v6.0.0/classes/ActionView/Helpers/FormHelper.html#method-i-check_box
Problem with all of these solutions is that it doesn't play well with the params hash on resubmits, so at the moment I'm using something like this,
# ApplicationHelper
def resolve_boolean_parameter resource, attribute, options = {}
default = options.delete(:default)
return default unless params[:utf8]
return params[resource][attribute] == "1"
end
and then in the view:
<div><%= f.label :accepts_newsletter, "Receive Newsletters" %>
<%= f.check_box :accepts_newsletter, :checked => resolve_boolean_parameter(:user, :accepts_newsletter, default: true) %>
</div>
New Function placed in your Helper
def check_if_true(item)
ActiveModel::Type::Boolean.new.cast(item)
end
In your View
<%= check_box("test", "active", {checked: check_if_true(#test.active) , :multiple => true, :style => "margin-left: 16px;"}, "true", "false") %>
This is how I did this now in 2020.
<%= form.check_box :with_cost, checked: true, class: '', type: 'checkbox', id: 'cost' %>
With the checked: true attribute.
Hope this helps.
If you are using the form helper in Rails 5.1 + to build your checkbox you have to pass in a hash the values with specific order.
= form.check_box :open_after, { class: 'form-control mt-1', data: {}, checked: true }, true, false
As you can see, inside the hash, first is class, next data and last checked. This works for me with Rails 6.0
I have a few check boxes in my view set to default as active:
<%= check_box "product[pr_attributes]", "ag_type", {:checked => #product.issenior?, :multiple => true, :checked => true}, checked_value = "ag:senior", unchecked_value = nil %>Senior(65-100)
The problem is, when I uncheck one of the defaults and save the changes, it defaults back to the checked state. How can I solve this?
Did you mean to have two option keys for :checked?
Mostly like the second one :checked => true is causing your problem.
i think the best way to do this in your case is use check_box_tag since your doing multiple answers for one attribute
syntax
check_box_tag "id", "value", "boolean_if_checked"
so in your case:
<%= check_box_tag "product[pr_attributes][]", "ag_type", #product.issenior?, { } %>
Then just add the other attributes on the hash after the #product.issenior?
This way, you can create multiple checkboxes for pr_attributes, and then when you submit the form, pr_attributes will be an array of your choices.
We used a migration to add a new field to our Posts table called new_choice:integer with :default => 1
On the edit form we made it a radio button with 3 choices A,B,C represented by values 1,2,3
When a NEW record is created, the "A" button will be selected by default.
However, when an already-existing record is edited, the current value is nil so NO radio button is selected.
Is there a way to have the erb form check a particular button (A/1) if the field value sis not the "valid" choices of 1,2,3?
This should work:
<%= f.radio_button :post, choice, :checked => #post.choice == choice ? true : false %>
The last option in radio button method will set the default, selected value:
radio_button("post", "new_choice", "1")
I'm using rails 2.3.4, which, when you call .check_box on the 'f' object in a form_for, makes a visible checkbox input for the 'checked' value, and a hidden checkbox input for the 'unchecked' value: http://railsbrain.com/api/rails-2.3.2/doc/index.html?a=M002434&name=check_box
The problem with this is that i have a validates_acceptance_of validation on the check_box, and if it's not checked, i'm getting a field_with_errors div wrapped around the visible checkbox AND the hidden checkbox, so that the error message appears twice.
In this instance i don't want a value passed through in the 'unchecked' case, so i don't want rails to add the hidden checkbox - this (switching off the hidden checkbox) would solve my problem. I can't figure out how to tell it to not add the hidden checkbox though. Can anyone tell me?
I know that i could get round this by making a check_box_tag, which doesn't add the hidden 'unchecked' case checkbox, but then i don't get field_with_errors stuff wrapped around the checkbox if it's not checked. Dispensing with the hidden field seems like the cleanest solution.
Thanks - max
In Rails 4 you can use include_hidden: false
example f.check_box :some_field, include_hidden: false
Since Rails 3.2, the hidden field will not be shown if the unchecked_value argument evaluates to false.
Example: f.check_box :your_field, {}, checked_value, false
See the Rails source: 3.2,
4.1
use <%= check_box_tag "your_model[your_field]" %>
f.check_box always gives you a hidden field.
So this is interesting. check_box takes four arguments as the method definition shows:
def check_box(object_name, method, options = {}, checked_value = "1", unchecked_value = "0")
Tags::CheckBox.new(object_name, method, self, checked_value, unchecked_value, options).render
end
The checked value and unchecked value must be the third and fourth argument. By setting an unchecked_value that evaluates to a truthy value, then the hidden input will appear.
My initial goal was to have a visible checkbox with a value of true, and a hidden checkbox with a value of false. So I tried doing this:
<%= f.check_box :share, { }, true, false %>
However, because I actually passed in a boolean value for unchecked value, it made the hidden field not appear at all! I tracked it down to this line of code in the Rails source:
def hidden_field_for_checkbox(options)
#unchecked_value ? tag("input", options.slice("name", "disabled", "form").merge!("type" => "hidden", "value" => #unchecked_value)) : "".html_safe
end
If #unchecked_value evaluates to false or nil, then no hidden input field would display. Now if you want to send true and false values rather than '1' or '0' using check_box helper, then you will need to wrap the booleans in strings:
<%= f.check_box :share, { }, 'true', 'false' %>
But if that's the case, you matters well just use the defaults of '1' and '0' for boolean values and let Rails handle it.
Rails stores booleans as TinyInt, at least for the MySQL database. Consequently, that '1' will get stored in the database as 1 and will be considered a true value.