Hello, I have two models, Product and ProductImage, and I'd like to offer the possibility to add up to 6 images to each product.
Product
has_many :product_images, :dependent => :destroy
while ProductImage
belongs_to :product
So far, my views are the following:
#products/_form.html.erb.
<% @product.product_images.build %>
<%= form_for(@product, :html => { :multipart => true }) do |product_form| %>
<% if @product.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@product.errors.count, "error") %> prohibited this product from being saved:</h2>
<ul>
<% @product.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= product_form.label :title %><br />
<%= product_form.text_field :title %>
</div>
<div class="field">
<%= product_form.label :description %><br />
<%= product_form.text_area :description %>
</div>
<div class="field">
<%= product_form.label :price %><br />
<%= product_form.text_field :price %>
</div>
<div id="product_images">
<%= render :partial => 'product_images/form', :locals => {:form => product_form} %>
</div>
<div class="actions">
<%= product_form.submit %>
</div>
<% end %>
and
#product_images/_form.html.erb
<%= form.fields_for :product_images do |product_image_form| %>
<div class="image">
<%= product_image_form.label :image, 'Image:' %>
<%= product_image_form.file_field :image %>
</div>
<% unless product_image_form.object.nil? || product_image_form.object.new_record? %>
<div class="image">
<%= product_image_form.label :_destroy, 'Remove:' %>
<%= product_image_form.check_box :_destroy %>
</div>
<% end %>
<% end %>
The question is: how do I force my partial form to print out 6 different file_fields, each with its own unique attribute name, e.g.:
name="product[product_images_attributes][0][image]"
name="product[product_images_attributes][1][image]"
and so on?
I mean, is that even possible or there is a better and different way to achieve such result?
I was thinking I could add as many fields with link_to and AJAX but I guess it's a lot easier for the user to have the six fields printed out and ready, instead of clicking a link each time in order to add a field.