问题
I have a page where I can view a product, and directly from this page the user can add and remove multiple images associated with the product. I'm using paperclip in a form to upload new file.
Because multiple images can be saved for a product I created an image model belonging to the product model. It's not possible to use the default paperclip file input because of the association. My solution below is working, but I'm wondering if there's a better way in rails to accomplish this without all the html that I hacked to make it work.
class Image < ActiveRecord::Base
belongs_to :product
class Product < ActiveRecord::Base
has_many :images, :dependent => :destroy
accepts_nested_attributes_for :images, :allow_destroy => true
show.html.erb
<% @product.images.build %>
<%= form_for(@product, :html => { :multipart => true }) do |f| %>
<input id="image" name="product[images_attributes][<%= @product.images.count %>][photo]" >size="30" type="file" onchange="this.form.submit();" />
<% end %>
回答1:
As you are most likely aware, in your controller you can build some empty file inputs with @product.images.build; whereas in your view for both edit and create you could do something like this:
<% f.fields_for :images do |img| %>
<% if img.object.data_file_name %>
<%= image_tag img.object.data.url(:thumb) %>
<%= link_to 'Delete', img.object, {:method => :delete, :confirm => 'Are you sure?'} %>
<% else %>
<%= img.file_field :data %>
<% end %>
<% end %>
This particular example requires an images controller with a destroy action, but it should work fairly well, even if the images are polymorphic.
来源:https://stackoverflow.com/questions/3260267/rails-paperclip-with-model-association