删除回形针图像Active Admin

Ric*_*wis 1 ruby ruby-on-rails paperclip formtastic activeadmin

我希望能够使用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
Run Code Online (Sandbox Code Playgroud)

因此,根据我所读的内容,可以将一个标志添加到我的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 
Run Code Online (Sandbox Code Playgroud)

在此阶段我在控制台中注意到的一点是,当单击进出复选框时,它的值不会更改为选中或取消选中; 应该是吗?

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
Run Code Online (Sandbox Code Playgroud)

这里有什么东西会导致这种情况无效,或者某人有这种设置的解决方案吗?

Ric*_*wis 6

希望这将有助于处于相同位置的人.您不需要在此处构建自定义方法来删除图像,只需在表单中使用它即可

 p.input :_destroy, as: :boolean, required: :false, label: 'Remove image'
Run Code Online (Sandbox Code Playgroud)

并在你的控制器(permit_params)通过

:_destroy
Run Code Online (Sandbox Code Playgroud)

在您的嵌套属性中,例如

 permit_params :title, :content, :news_category_id, :author,
            news_images_attributes: [:id, :photo, :post_id, :_destroy]
Run Code Online (Sandbox Code Playgroud)

  • 我正在使用rails 3.我通过在模型中使用attr_accessor和attr_accessible来实现它. (2认同)