views:

75

answers:

1

I'm running into a problem viewing a list of 'category' checkboxes when I try to nest them in a fields_for form.

I have a 'product' model that 'has_many' 'photos' which 'has_and_belongs_to_many' 'categories'. I'm pretty sure all my associations in my models are correct, as is my joins table for the 'photos' and 'categories' relationship.

Nesting just the 'photo' inside the 'product' works for me:

<%= form_for(@product) do |f| %>

  <div class="field">
    <%= f.label :name %><br />
    <%= f.text_field :name %>
  </div>

  <div class="field">
    <% f.fields_for :photos do |builder| %>
            <%= builder.label :name, "Photo name" %>
            <%= builder.text_field :name %>
      <% end %>
  </div>

  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

But I can't add the 'category' model with the checkboxes. Here's what doesn't work:

    <%= form_for(@product) do |f| %>

      <div class="field">
        <%= f.label :name %><br />
        <%= f.text_field :name %>
      </div>

      <div class="field">
        <% f.fields_for :photos do |builder| %>
                <%= builder.label :name, "Photo name" %>
                <%= builder.text_field :name %>

                <div class="field">
                   Categories:
                   <% for category in Category.find(:all )%>
                      <%= check_box_tag "photo[category_ids][]", category.id, @photo.categories.include?(category) %>
                      <%= category.name %>
                   <% end %>
                </div>

          <% end %>
      </div>

      <div class="actions">
        <%= f.submit %>
      </div>
    <% end %>

The check_box_tag and the the lack of a form helper when cycling through the category list is screwing me up. Can anyone please help? Thanks.

UPDATE: I can get it to work with this selector box, but I'm trying to get it to work with the checkboxes:

<%= f.collection_select :category_ids, Category.find(:all, :order => 'name'), :id, :name, {}, :multiple => true %>
A: 

have you checked into accepts_nested_attributes_for

Here is an example of how to get HABTM to work with accepts_nested_attributes_for

http://patshaughnessy.net/2010/4/4/creating-associations-to-existing-data-part-3-has_many-through-scaffolding

heavysixer
I'm using 'accepts_nested_attributes_for' in my product model (which has_many photos) but Im not using it in my photo model (which has_and_belongs_to_many categories).
jrs