2010-07-07 24 views
0

讓我們想象一下,我爲特定記錄自定義圖像上傳,並向模型中添加兩​​列。ActiveRecord自定義字段方法

thumbnail_url thumbnail_path

現在,讓我們想象一下,我有一個表格:這是多形式上傳的文件文件中的字段。我需要以某種方式讓模型拾取給定哈希中的文件,然後將其發佈到自定義方法,該方法執行上載並將其另存爲模型。

現在我這樣做:

def initialize(options = nil) 
    if options 
    if options[:file] 
     self.upload_thumbnail(options[:file]) 
     options.delete(:file) 
    end 
    super options 
    else 
    super 
    end 
end 

def update_attributes(options = nil) 
    if options 
    if options[:file] 
     self.upload_thumbnail(options[:file]) 
     options.delete(:file) 
    end 
    super options 
    else 
    super 
    end 
end 

它的工作原理,但我在這裏做一些不必要的覆蓋。有沒有更簡單的方法來做到這一點?一些只需要重寫一種方法的東西?

回答

2

您正在尋找virtual attributes。只要定義:

def file 
    # Read from file or whatever 
end 

def file=(value) 
    # Upload thumbnail and store file 
end 

initializeupdate_attributes和表兄弟將挑選方法爲您服務。

這樣,或者節省了麻煩,並使用paperclip作爲坎達達建議。

0

您是否考慮過使用paperclip寶石?它執行您在問題中描述的功能。