2012-06-13 33 views
1

我有一个模型“文章”has_many“资产”这是一个多态模型,我附加图像使用回形针。 当我编辑文章,我想能够删除旧图像,并添加一个新的一个在同一笔画。我正在使用fields_for,因为the Rails API says我可以将它用于资产的特定实例,所以fields_for似乎具有多功能性。因此,这里是我的表单的相关部分:如何删除一个回形针附件,并创建另一个一举

表:

=f.fields_for :assets do |ff| 
    =ff.label "image" 
    =ff.file_field :image 

-unless @article.assets.first.image_file_name.nil? 
    [email protected] do |asset| 
    =f.fields_for :assets, asset do |fff| 
     =image_tag(asset.image.url(:normal)) 
     =fff.label "delete image" 
     =fff.check_box :_destroy 

第一fields_for是添加图片的文章,第二部分是删除已经存在的资产。这种形式可以添加资产,删除资产,但它不能同时进行。 这是问题。 我怀疑check_box没有足够的指示或什么。

资产型号:

class Asset < ActiveRecord::Base 
    belongs_to :imageable, :polymorphic => true 

    has_attached_file :image, :styles => { :normal => "100%",:small => "100 x100>",:medium => "200x200>", :thumb => "50x50>" }, 
         :storage => :s3, 
         :s3_credentials => "#{Rails.root}/config/s3.yml", 
         :path => "/:attachment/:id/:style/:filename" 

条控制器/编辑:

def edit 
    @article = Article.find(params[:id]) 
    @assets = @article.assets 
    if @assets.empty? 
     @article.assets.build 
    end 
    end 

我期待您的答复。

回答

3

随着我可怜的哀嚎失声,我不得不独自出发(可能是最好的)。我通过摆弄窗体的逻辑来发现解决方案。下面是设置了,让我增加一个回形针附件,删除一个(或多个)的一种形式提交:

形式:

= form_for(@article, :action => 'update', :html => { :multipart => true}) do |f| 
. 
. 
. 
    [email protected] do |asset| 
     =f.fields_for :assets, asset do |asset_fields| 
      -if asset_fields.object.image_file_name.nil? 
      =asset_fields.label "image" 
      =asset_fields.file_field :image 
      -else 
      =image_tag(asset_fields.object.image.url(:normal)) 
      =asset_fields.check_box :_destroy 

我的设立是:一个article的has_many assets这是一个多态模型,为我保存图像附件。

研究:

http://apidock.com/rails/ActionView/Helpers/FormHelper/fields_for

creating a form for deleting uploads that belongs to products

- 第二环节:提供洞察使用object方法由fields_for提供的形式帮助,在我的情况下,它是asset_fields.object...这让我乱与@assets

实例这里是感兴趣的文章控制器方法:

def edit 
    @article = Article.find(params[:id]) 
    @assets = @article.assets 
    @article.assets.build 
    end 
相关问题