Rails Paperclip with model association

烂漫一生 提交于 2020-01-05 08:00:04

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!