简体   繁体   English

与模型关联的Rails回形针

[英]Rails Paperclip with model association

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. 我下面的解决方案正在工作,但是我想知道是否有一种更好的方法可以在没有我为了使它工作而入侵的所有html的情况下实现这一目标。

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 %>

As you are most likely aware, in your controller you can build some empty file inputs with @product.images.build ; 如您所知,您可以在控制器中使用@ 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. 这个特殊的示例需要一个具有破坏动作的图像控制器,但是即使图像是多态的,它也应该可以很好地工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM