2014-05-20 81 views
1

我無法獲得此before_save過濾器的工作。我想,我的方法很標準。圖像通過回形針上傳。回形針,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_... PARAMS都通過了,什麼也沒有,雖然刪除:

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

有什麼想法?謝謝。

更新

即使它簡化到這不起作用:

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

而且"remove_banner"=>"1"在PARAMS來通過。 u.banner.clear然後u.banner.save在控制檯中正常工作。

+0

當你銷燬'#{a}'.to_sym - 數據存儲在哪裏?它是否已經在數據庫中,或者是參數散列的一部分? –

+0

'#{a}'表示模型中的每個Paperclip附件。 –

回答

0

我已經作出關心像這樣解決了這個:

# 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回答一個巨大的線索。