我希望能够使用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
这里是否有任何东西会导致此方法不起作用,或者有人对这种设置有解决方案?
希望这会帮助处于相同位置的人。您无需建立自定义方法即可在此处删除图像,只需在表单中使用它即可
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]
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句