如何通过carrierwave删除nested_form中的资产?
美好的一天。 是否有人在Carrierwave中以嵌套形式删除资产的解决方案?如何通过carrierwave删除nested_form中的资产?
模型
has_many :article_images, :dependent => :destroy
accepts_nested_attributes_for :article_images
mount_uploader :image, ImageUploader
belongs_to :article, :polymorphic => true
schema.rb
create_table "article_images", :force => true do |t|
t.string "image"
t.string "article_id"
end
create_table "articles", :force => true do |t|
t.string "title"
end
控制器
def edit
@article = Article.find(params[:id])
@article.article_images.build
end
VIEW
_form.html.erb
<%= f.fields_for :article_images do |article_image| %>
<% if article_image.object.new_record? %>
<%= article_image.file_field :image %>
<% else %>
<%= image_tag(article_image.object.image.url(:thumb)) %>
<%= article_image.check_box :remove_image %> #DON'T WORK
<% end %>
<% end %>
,如果你在你的模型添加到您的accepts_nested_attributes_for会发生什么:
accepts_nested_attributes_for :article_images, :allow_destroy => true
,并改变这个在您的视图代码:
<%= article_image.check_box :remove_image %> #DON'T WORK
要这样:
<%= article_image.check_box :_destroy %> #MIGHT WORK?
它的作品,但留在自己的空文件夹。 – itsnikolay 2012-04-01 06:47:13
爱你adam :)使用nested_for _destroy来破坏对象;) – 2013-09-23 12:08:41
我认为这是更好如果你这样做:
class ArticleImage < ActiveRecord::Base
# ...
attr_accessible :remove_image
after_save :clean_remove_image
def changed?
!!(super || remove_image)
end
def clean_remove_image
self.remove_image = nil
end
end
它为我工作。
我实际上遇到了一个与旧版本的Mongoid类似的问题。只是'改变?'方法覆盖为我工作。它看起来像嵌套的对象没有被标记为脏,除非模型中的另一个字段在尝试删除图像的同时也被更新。 – 2014-09-03 21:15:17
[https://github.com/itsNikolay/carrierwave_multiply_files_upload](https://github.com/itsNikolay/carrierwave_multiply_files_upload)所有的代码和回购有 – itsnikolay 2012-03-31 15:53:50