dynamic check_box using field_for in rails
- by Craig Whitley
I have a many-to-many relationship with a link box, and I want to pull those models together into one form so I can update from the same page. I'm really struggling with getting the check_box to even show all the elements of my array - I've scoured the net and been working on this literally all day, and I'm finding it difficult to apply the information I'm reading to my problem. I'm also extremely new to RoR and I've been following a bit of an outdated video tutorial (pre 2.0) so apologies for my code. So far, I've got it to output only one key pair in the array (the last one) - although outside the form, the code used in the tutorial works exactly how it should. Thats of little use though! Host is the model for which the main form is for, and Billing is the outside model that I'm trying to add to the form.
This is the code that works outside of the form from the tutorial:
<% for billing in @billings -%>
<%= check_box_tag('billing_title[]', billing.id, @host.billings.collect
{|obj| obj.id}.include?(billing.id))%> <%= billing.title %><br />
<% end -%>
I just need to know how to make it work inside the form. This is the aforementioned code that only retrieves the last array keypair after looping through them:
<% f.fields_for :billings do |obj| %><br />
<%= check_box_tag('billing_title[]', billing.id, @billings.collect
{|obj| obj.id}.include?(billing.id))%> <%= billing.title %><br />
<% end %>
The debug(@billings) :
---
- !ruby/object:Billing
attributes:
title: Every Month
id: "1"
attributes_cache: {}
- !ruby/object:Billing
attributes:
title: 12 Months
id: "2"
attributes_cache: {}
- !ruby/object:Billing
attributes:
title: 6 Months
id: "5"
attributes_cache: {}
Any help really appreciated.