2010-12-11 75 views
0

如何根據創建或更新記錄來在模型內部做些什麼?我相信這很簡單,但我似乎無法弄清楚。導軌模型回調

這些是用回形針更新或創建附件的不同樣式。

class Photo < ActiveRecord::Base 

    belongs_to :product 

    #after_upate :flag_somthin 

    Paperclip.interpolates :product_id do |attachment, style| 
    attachment.instance.product_id 
    end 

    has_attached_file :data, 
    :storage => 's3', 
    :s3_credentials => "#{RAILS_ROOT}/config/s3_credentials.yml", 
    :bucket => 'leatherarts.com', 
    :s3_host_alias => 'leatherarts.com.s3.amazonaws.com', 
    :url => ':s3_alias_url', 
    :path => "images/products/:product_id/:style/:basename.:extension", 
    :styles => lambda { |style| style.instance.choose_styles }, 
    :default_style => :medium, 
    :default_url => 'http://leatherarts.com.s3.amazonaws.com/images/records/m1.png', 
    :s3_headers => { 'Expires' => 2.months.from_now.httpdate } 

    validates_attachment_presence :data 
    validates_attachment_size :data, :less_than => 10.megabytes 
    validates_attachment_content_type :data, :content_type => ['image/jpeg','image/gif','image/png'] 

    def choose_styles 
     { :thumb => "60x60#", :small => "200x200>", :medium => "400x400>", :large => "1000x1000>", :backup => "2000x2000>" }, :on => :create 
     { :thumb => "60x60#", :small => "200x200>", :medium => "400x400>", :large => "1000x1000>" }, :on => :update 
    end 

end 

回答

3

使用new_record?方法返回不同的散列:

def choose_styles 
    defaults = { :thumb => "60x60#", :small => "200x200>", :medium => "400x400>", :large => "1000x1000>" } 
    defaults.merge! :backup => "2000x2000>" if new_record? 
    defaults 
end 
+0

是啊,這就是我想要做的一般,但我不知道如何完成它在這種情況下,我更新了我的問題與更多細節。 – holden 2010-12-11 19:19:25

+1

我更新了我的答案以更好地回答問題。 – tjwallace 2010-12-11 20:12:01

+0

爲什麼你想通過多次更新保留原始照片?這聽起來像它應該存儲在不同的記錄。 – klochner 2010-12-11 21:43:02