【问题标题】:Remove paperclip images Active Admin删除回形针图像 Active Admin
【发布时间】:2014-02-17 20:13:06
【问题描述】:

我希望能够使用 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 模型中,并有一个 before save 方法可以删除该图像。我设想它看起来像这样,但单击复选框时不会删除图像。

#/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

这里有什么会导致这不起作用,或者有人有这种设置的解决方案吗?

【问题讨论】:

    标签: ruby-on-rails ruby paperclip activeadmin formtastic


    【解决方案1】:

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

     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]
    

    【讨论】:

    • 我得到未知属性:_destroy
    • 您是否已将_destroy 添加到允许的参数中?你用的是rails 3还是4?
    • 我正在使用 rails 3。我通过在模型中使用 attr_accessor 和 attr_accessible 使其工作。
    • 不需要使用attr_accesor
    • 对于其他错过它的人,请务必包含 OP 的 before save :remove_photoremove_photo 私有方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-27
    • 1970-01-01
    • 2023-03-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多