Rails: form_for checkbox set to true or false whether the box is checked/unchecked
Solution 1
Rails will do this for you when your form is acting on an object, just leave all the extra stuff off the tag like so:
<div class="field">
<%= f.label "Get Email" %> <br />
<%= f.check_box :send_email %> <br />
</div>
And it should all start working as you expect. The checkboxes will be ticked if the attribute is true, and vice versa the checked state when you submit the form will affect the attribute. Rest of your code is fine.
Solution 2
Further informations about forms and updating database
Indeed, the last answer is right : using the form_for syntax is enough and Rails will do the association unchecked:false / checked:true for you.
<div class="field"> <%= f.label "Get Email" %> <br /> <%= f.check_box :send_email %> <br /> </div>
I had the same problem even with that syntax. The fact is the server's console returned me Unpermitted parameter: checkbox_value
: don't forget to update your required/permitted parameters to put into params
! And in my case :
# ***_controller.rb
private
def operator_params
params.require(:operator).permit(:name, :website, :checkbox_value, :global)
end
Solution 3
I had same problem.I did
<% @batches.each do |batch| %>
<div class="name_list<%=cycle('odd', 'even')%>"><li>
<label><%= check_box_tag "send_sms[batch_ids][]", batch.id,false,:class=>'right' %>
<div class="att_list_names"> <%= batch.full_name %></div> </label>
</li> </div>
<% end %>
user2158382
Updated on June 10, 2020Comments
-
user2158382 almost 4 years
I have a model called users that has 2 boolean attributes
send_email
andsend_text
. I have a form that edits the User model, and I want it to set those attributes to true/false depending on whether the box is check/unchecked. Here is my form<%= form_for(@user) do |f| %> <div class="field"> <%= f.label :email %> <br /> <%= f.text_area :email %> <br /> </div> <div class="field"> <%= f.label :cell %> <br /> <%= f.text_area :cell %> <br /> </div> <div class="field"> <%= f.label "Get Email" %> <br /> <%= f.check_box :send_email, {}, true, false %> <br /> </div> <div class="field"> <%= f.label "Get Text" %> <br /> <%= f.check_box :send_text, {}, true, false %> <br /> </div> <div class="actions"> <%= f.submit "Submit", class: "button small radius" %> <%= link_to "go back", @user, class: "button small radius secondary" %> </div> <% end %>
And here is the
update
action of theuser_controller
def update @user = User.find(params[:id]) @user.update_attributes(params[:user]) redirect_to @user end
The form and update looks like it works perfectly, but when i submit this form with the send_email or send_text box checked, it does not change the attributes of the user model (send_email,send_text) to false