Zoe Zoe - 4 months ago 19
Ruby Question

Saving checkbox value in erb - rails

I have a nested form that saves information to three different models. One section of the form uses checkboxes and is supposed to save values 1-5. However, even when the boxes are checked the form returns value 0. I have tried several different variations of code for setting the checked value. Any help would be much appreciated. A section of the form code is below:

<%= form_for @newinstructor do |f|%>

<%= f.text_field :first_name %>
<%= f.text_field :last_name %>
<%= f.fields_for :through_ats do |tag_field| %>
<%= label_tag("What categories does your activity fit into?") %><br>
<%= label_tag(:tag, "Cooking") %>
<%= tag_field.check_box(:tag_id, :value => 1) %>
<%= label_tag(:tag, "Art") %>
<%= tag_field.check_box(:tag_id, :value => 2) %>
<%= label_tag(:tag, "Music") %>
<%= tag_field.check_box(:tag_id, :value => 3) %>
<%= label_tag(:tag, "Outdoors") %>
<%= tag_field.check_box(:tag_id, :value => 4) %>
<%= label_tag(:tag, "Food") %>
<%= tag_field.check_box(:tag_id, :value => 5) %>
<% end %>

<%= f.submit %>

<% end %>

Zoe Zoe
Answer

To fix the problem I had, I had to uniquely define each of the symbols in tag_field.checkbox, then require/permit them individually in params

so in the form i put:

<%= label_tag("Please check off the categories your activity fits into.") %><br>
    <%= label_tag(:tag, "Cooking") %>
    <%= tag_field.check_box(:cooking) %>
    <%= label_tag(:tag, "Art") %>
    <%= tag_field.check_box(:art) %>

instead of :

<%= label_tag("What categories does your activity fit into?") %><br>
    <%= label_tag(:tag, "Cooking") %>
    <%= tag_field.check_box(:tag_id, :value => 1) %>
    <%= label_tag(:tag, "Art") %>
    <%= tag_field.check_box(:tag_id, :value => 2) %>

and in the controller:

params.require(:instructor).permit(through_ats: [:cooking, :art, :music, :outdoors, :food])

instead of:

params.require(:instructor).permit(through_ats: [:id, :tag_id])
Comments