2013-03-16 84 views
4

我現在使用Carrierwave上傳圖像。所有不錯,除了一個, - 當我添加複選框刪除上傳的圖像時,我得到錯誤:「無法批量分配受保護的屬性:remove_image」。Carrierwave無法刪除圖像

形式:

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

型號:

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 

者:

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 

我認爲Carrierwave一定要利用:remove_image,但不這樣做。這段代碼有什麼問題?

回答

14

只需將remove_image添加到您的attr_accessible列表