繁体   English   中英

删除回形针图像Active Admin

[英]Remove paperclip images Active Admin

我希望能够使用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]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM