1

I can't get this before_save filter to work. My methods are pretty standard, I think. Images are uploaded via Paperclip.

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

The remove_... params are passed, nothing's deleted though:

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

Any thoughts? Thanks.

Update

Even simplifying it to this doesn't work:

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

And "remove_banner"=>"1" comes through in the params. The u.banner.clear then u.banner.save works fine in the console.

t56k
  • 6,769
  • 9
  • 52
  • 115

1 Answers1

0

I've solved this by making a concern like so:

# 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

And just including the concern wherever need be. Thanks to this answer for a huge clue.

Community
  • 1
  • 1
t56k
  • 6,769
  • 9
  • 52
  • 115