Rails check box resetting to default - ruby-on-rails

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.

Related

Use checkbox with conditions in 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.

Stored value not being set to nil when user deselects all options - rails / simple_form

I have the following form input which is working, except for one small 'bug'
<%= f.input :secondary_role, :collection => UseridRole::VALUES, :include_blank => false,:label => "Secondary Role(s):", :input_html => { :class => " simple_form_bgcolour simple_form_position overide_selection_field_width", :size => 4, multiple: true }, include_hidden: false, :hint => "Hold shift to select multiple roles" %>
My user's secondary role is stored in my DB as an array:-
"secondary_role": ["moderator"]
My problem is that in cases where the user has set a secondary role, that can't be un-set by deselecting the option. Nothing happens when an option is deselected in the list and saved. The above moderator can only be removed by selecting another option. How can I make the array empty upon deselection of all?
Remove the include_hidden: false option; the hidden field is there to make this work automatically.
(Otherwise, you'll need to handle the situation manually in the controller action that receives the form submission.)
So as #matthewd pointed out, the solution was to remove the include_hidden: false option, although this introduced another issue of a blank array item being added to my roles array.
So, I added the below method to trigger before every save and remove any blank array entries:
def remove_blank_entry
secondary_role = self.secondary_role
if secondary_role.include? ""
secondary_role.delete("")
end
end

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 set a field read only in rails 3.1.0 views?

My question is how to set a field in rails form read only. The following is a selection box in quotes controller. Users are not allowed to change the selection.
<% #quote.test_items.each do |t| %>
<%= f.association :test_items, :label => false, :selected => t.id %>
<% end %>
The app uses simple_form. Thanks so much.
I've encountered a similar problem, thankfully, there is a simple resolution.
The basic issue is that if you use :disabled => true with simple_form you will not see that value back in the controller. When you pass an object from HTML form to later bind it to the model - you need all of those attributes. The :disabled => true however does not pass any such attribute.
The solution to this is to use :readonly => true - it will protect the field from user entry and it will still pass the param value back to the controller so you can bind everything to your model.
Good luck.
See https://github.com/plataformatec/simple_form/pull/367
I believe you'd just pass in :disabled => true. It's been my experience that options 'just work' with simple_form. So in your case:
<% #quote.test_items.each do |t| %>
<%= f.association :test_items, :label => false, :disabled => true, :selected => t.id %>
<% end %>
From the simple_form github repo:
It is also possible to give the :disabled option to SimpleForm, and it'll automatically mark the wrapper as disabled with a css class, so you can style labels, hints and other components inside the wrapper as well.
Yes, what #gk0r said, as it is documented here:
NOTE: The HTML options disabled, readonly, and multiple can all be treated as booleans. So specifying :disabled => true will give disabled="disabled".
*disabled will have slightly different behavior than readonly.
The top answers above are all wrong.
disabled attribute has a different behaviour than readonly.
read and compare them:
http://www.w3schools.com/tags/att_input_disabled.asp
Tip: Disabled elements in a form will not be submitted.
http://www.w3schools.com/tags/att_input_readonly.asp
The right answer is to use
:readonly => true
something like this:
<%= f.association :test_items, :label => false, :readonly => true, :selected => t.id %>
It's not clear to me if the association method accepts HTML options or not, but if it does, you can pass disabled: 'disable' to make it read-only with a fixed value.
I think you might be able to choose the fixed value by passing association as block, as shown in the association docs:
f.association :company do |c|
c.input :name, selected: 'selection'
c.input :type
end
As to whether or not the entire list can be read-only and still drop-down, the only solutions I see from google involve JS, for example:
http://techeyes.blogspot.com/2007/11/making-html-select-readonly.html

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