与模型关联的Rails回形针 [英] Rails Paperclip with model association

查看:143
本文介绍了与模型关联的Rails回形针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个页面可以查看产品,并且用户可以直接从该页面添加和删除与该产品关联的多个图像.我正在使用回形针上载新文件.

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.

因为可以为一个产品保存多个图像,所以我创建了一个属于该产品模型的图像模型.由于存在关联,因此无法使用默认的回形针文件输入.我下面的解决方案正在工作,但我想知道是否有一种更好的方法可以在没有我为使之工作而入侵的所有html的情况下实现这一目标.

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 Image < ActiveRecord::Base
belongs_to :product

class Product < ActiveRecord::Base
has_many :images, :dependent => :destroy accepts_nested_attributes_for :images, :allow_destroy => true

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

推荐答案

如您所知,在控制器中,您可以使用 @ product.images.build 构建一些空文件输入.而在您看来,无论是编辑还是创建,您都可以执行以下操作:

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.

这篇关于与模型关联的Rails回形针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆