2012-06-13 32 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 
相關問題