2014-02-17 25 views
1

我希望能夠使用Active_admin中的formtastic在我的編輯表單中刪除圖像。有很多關於這個的帖子,但我似乎無法得到它適合我的設置出於某種原因。刪除回形針圖像活動管理

我有一個Post模型和保持圖像的每個職位的NewsImages模型:

class Post < ActiveRecord::Base 

    has_many :news_images, dependent: :destroy 
    accepts_nested_attributes_for :news_images, allow_destroy: true 

end 


class NewsImage < ActiveRecord::Base 
    belongs_to :post 
    has_attached_file :photo 

end 
從我讀一個標誌可以添加到我的NewsImage模型,並有

因此,一個之前保存方法將刪除該圖像。我設想它看起來像這樣但點擊複選框時不會刪除圖像。

#/admin/post.rb 
    f.has_many :news_images do |p| 
    if p.object.new_record? 
     p.input :photo, as: :file 
    else 
    p.input :photo, as: :file, :hint => p.template.image_tag(p.object.photo.url(:thumb)) 
    p.input :remove_image, as: :boolean, required: :false, label: 'Remove image' 

    end 
    end 

東西,我已經在這個階段控制檯中注意的是點擊複選框它的價值不會改變,以選中或取消選中...是應該的進出是什麼時候?

NewsImage模型現在看起來像

class NewsImage < ActiveRecord::Base 
    before_save :remove_photo 
    belongs_to :post 

    private 

    def remove_photo 
    self.photo.destroy if self.remove_image == '1' 
    end 

end 

有什麼在這裏,任何人都可以看到,將導致此不工作,還是有人對這種設置的一個解決方案?

任何幫助讚賞

回答

6

希望這將有助於某人在同一位置。你不需要建立一個自定義的方法,在這裏刪除圖片,您只需使用此表單中的

p.input :_destroy, as: :boolean, required: :false, label: 'Remove image' 

,並在控制器(permit_params)通過

:_destroy 
您的嵌套屬性中

,如

permit_params :title, :content, :news_category_id, :author, 
      news_images_attributes: [:id, :photo, :post_id, :_destroy] 
+0

我得到未知的屬性:_destroy – buddy

+0

您是否在允許的參數中添加了_destroy?你使用軌道3或4? – Richlewis

+2

我正在使用rails 3.我通過在模型中使用attr_accessor和attr_accessible來實現它。 – buddy