【问题标题】:Paperclip, before_save, and deleting attachments回形针、before_save 和删除附件
【发布时间】:2014-06-10 14:00:22
【问题描述】:

我无法让这个before_save 过滤器工作。我认为我的方法很标准。图片通过回形针上传。

before_save :remove_checked_attachments

def attachments
  %w(banner footer logo accreditation)
end

private

def remove_checked_attachments
  attachments.each do |a|
    if "remove_#{a}".to_sym && !"#{a}_updated_at_changed?".to_sym
      "#{a}".to_sym.destroy
    end
  end
end

remove_... 参数已通过,但没有任何内容被删除:

... "remove_banner"=>"1" ...

有什么想法吗?谢谢。

更新

即使把它简化成这样也行不通:

after_validation { banner.clear if remove_banner == '1' }

"remove_banner"=>"1" 在参数中通过。 u.banner.clear 然后 u.banner.save 在控制台中可以正常工作。

【问题讨论】:

  • 当你destroy#{a}.to_sym - 数据存储在哪里?它已经在数据库中,还是参数哈希的一部分?
  • #{a} 代表模型中的每个回形针附件。

标签: ruby-on-rails ruby-on-rails-3 paperclip before-save


【解决方案1】:

我已经通过提出这样的问题解决了这个问题:

# must be included after attachment declarations in model
module RemoveAttachment
  extend ActiveSupport::Concern

  included do
    attachment_definitions.keys.each do |name|

      attr_accessible :"remove_#{name}"
      attr_accessor :"remove_#{name}"

      before_validation { send(name).destroy if send("remove_#{name}") == '1' }

      define_method :"remove_#{name}=" do |value|
        instance_variable_set :"@remove_#{name}", value
        send("#{name}_file_name_will_change!")
      end

    end
  end
end

并且只要在需要的地方包括关注。感谢this 提供了一个巨大的线索。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-23
    • 1970-01-01
    • 1970-01-01
    • 2016-01-20
    • 2011-06-14
    • 1970-01-01
    相关资源
    最近更新 更多