Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Carrierwave cannot remove image

I'm using Carrierwave for uploading image now. All nice, except one, - when I add checkbox for removing uploaded image I get error: "Can't mass-assign protected attributes: remove_image".

Form:

...
<%= f.check_box :remove_image %>
<%= f.label :remove_image, "remove image" %>
...

Model:

class Manufacturer < ActiveRecord::Base

  attr_accessible :name, :alias, :short_description, :long_description, :image, :publish,
  :position, :meta_keywords, :meta_description, :meta_title

  mount_uploader :image, ManufacturerUploader

  validates_presence_of :name, :alias
  validates_uniqueness_of :name, :alias
  validates_format_of :alias, :with => /^[a-z\d\-]*$/, :message => "a-z, 0-9 \' - \' ONLY"

  default_scope order('position ASC')

  before_destroy :remember_image
  after_destroy :remove_img

  protected
  def remember_image
    @image_name = self[:image]
  end

  def remove_img
    File.delete("#{Rails.root}/public/images/manufacturer/#{@image_name}")
    File.delete("#{Rails.root}/public/images/manufacturer/thumb_#{@image_name}")
  end

end

Uploader:

class ManufacturerUploader < CarrierWave::Uploader::Base

 include CarrierWave::MiniMagick
 include Sprockets::Helpers::RailsHelper
 include Sprockets::Helpers::IsolatedHelper

 storage :file

 before :store, :remember_cache_id
 after :store, :delete_tmp_dir

 def remember_cache_id(new_file)
   @cache_id_was = cache_id
 end

 def delete_tmp_dir(new_file)
   if @cache_id_was.present? && @cache_id_was =~ /\A[\d]{8}\-[\d]{4}\-[\d]+\-[\d]{4}\z/
      FileUtils.rm_rf(File.join(root, cache_dir, @cache_id_was))
   end
 end

def store_dir
  "images/#{model.class.to_s.underscore}"
end

def default_url
  "" + [version_name, "default.jpg"].compact.join('_')
end

process :resize_to_fit => [300, 300]

version :thumb do
   process :resize_to_fit => [150, 150]
end

def extension_white_list
   %w(jpg jpeg gif png)
end

def filename
  "#{secure_token(10)}.#{file.extension}" if original_filename.present?
end

protected
def secure_token(length=16)
  var = :"@#{mounted_as}_secure_token"
  model.instance_variable_get(var) or model.instance_variable_set(var, SecureRandom.hex(length/2))
end

end

I think Carrierwave must to leverage :remove_image, but don't do it. What's wrong in this code?

like image 264
Alexander Shlenchack Avatar asked Dec 04 '22 12:12

Alexander Shlenchack


1 Answers

Simply add remove_image to your attr_accessible list

like image 180
apneadiving Avatar answered Dec 07 '22 02:12

apneadiving