Use checkbox with conditions in rails - ruby-on-rails

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.

Related

How to make a check_box checked in rails?

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

How to preselect dropdown given info from database to select_tag?

I have this line and after it is submitted as a form, C7000 or C3000 gets stored as a string. For the edit page, I cannot get the stored value to be the preloaded option on the dropdown instead of "Select One". What am I doing wrong?
= select_tag :enclosure_model, "<option>Select One</option><option>C7000</option><option>C3000</option>".html_safe, :disabled => false
Thanks
<%= select_tag :enclosure_model, helper.options_for_select([["select one", ""], ["c700"], "c700"], "c700"), :disabled => false %>
The above code will select c700

How to set the value of radio button after submitting form?

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"))

Rails check box resetting to default

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.

Preselect Check box with Rails Simple_form

I'm using Simple_Form with Rails 3 and it's great. I have a simple question. I can create a check box using f.input if the type is boolean behind the scenes. However, I would like it to be preselected as true.
Is there a way to do this via the view?
If you don't want to, or cannot update your migration to do 'PerfectlyNormal's answer, then you can add the following to the end of your f.input:
:input_html => { :checked => true }
So, it would become:
= f.input :some_flag, :input_html => { :checked => true }
the best way would be to set the default value in your model, something like
create_table :my_table do |t|
...
t.boolean :my_boolean, :default => true
...
end
which simple_form will pick up on, and set the checkbox to be checked by default.
A simpler way is to do it as Dave says, and just force the value to 1, but if a validation fails, and you display the form again, it will still be checked, regardless of how it looked when the form was submitted.
It Worked for me which checks only one checkbox with value of "None"
<%= f.input :notify, label: "Notification", as: :check_boxes, collection: ["None", "Daily", "Weekly", "Monthly", "Quarterly", "Yearly"], :item_wrapper_class => 'inline', :checked => ["None", true] %>
I just stumbled over this post and what worked for me is similar to the latest answer - but shorter. Just initialize the Object with the wished setting:
def new
Object.new(my_boolean: true)
end
In my opinion, the rail way to do this would be to set the value of the attribute in the controller:
#some_object.some_flag = 1
This should work:
= f.input :some_flag, :input_html => { :value => '1' }
If you do the following, as in the highest rated answer (and as noted by #PerfectlyNormal) you are essentially hard-coding the state for every page load:
= f.input :some_flag, :input_html => { :checked => true } # don't do this
If you are using Rails-style server validation, this will have the unintended side effect of resetting the user's choice when validation fails.
Defaulting it in the model is ideal if the default value is static. In some cases though, the default value is driven by some business rule, so setting it at runtime is desired. For example, in my case, I wanted to default a checkbox to true, but only for certain types of organizations.
What you want is to default the value only when it is not already set, otherwise use the user-selected value. Here's how I handled this:
- is_checked = #org.is_special.nil? ? true : #org.is_special?
= f.input :some_flag, :input_html => { :checked => is_checked }
For Rails 6+, you can simply do:
<%= f.check_box :remember_me, checked: true %>

Resources