2010-10-27 47 views
4

使用Rails 2,我嘗試通過回形針模型中的另一個模型區分不同的動態圖像大小。我目前的做法,用一個Proc,看起來如下:帶有動態樣式大小的回形針附件,型號爲

class File < ActiveRecord::Base 
    has_many :sizes, :class_name => "FileSize" 
    has_attached_file(
    :attachment, 
    :styles => Proc.new { |instance| instance.attachment_sizes } 
) 

    def attachment_sizes 
    sizes = { :thumb => ["100x100"] } 
    self.sizes.each do |size| 
     sizes[:"#{size.id}"] = ["#{size.width}x#{size.height}"] 
    end 
    sizes 
    end 
end 

class FileSize < ActiveRecord::Base 
    belongs_to :file 

    after_create :reprocess 
    after_destroy :reprocess 

    private 

    def reprocess 
    self.file.attachment.reprocess! 
    end 
end 

似乎一切都迎刃而解,但顯然沒有風格處理和正在創建無圖像。

有沒有人管理過像這樣的東西?

- 更新 -

顯然對實例的方法attachment_sizes有時不是#定義 - 但不應實例實際上是#? 對我來說,這看起來像改變實例..

回答

2

的解決方案是簡單。 instance在我的第一個例子中Proc是Paperclip :: Attachment的一個實例。當我想調用一個方法File,一個已經拿到了proc中調用實例:

Proc.new { |clip| clip.instance.attachment_sizes } 

instance代表在給定的例子File -instance。

1

我假設你有一切與回形針工作,這樣你上傳了一個圖像,現在proc只是不工作。

它應該工作。儘量不要將大小放入數組中。

你這樣做

sizes = { :thumb => ["100x100"] } 

但我有它在那裏我不把規模在ARRY

sizes = { :thumb => "100x100" } 

給一個嘗試:)

+0

嗨,謝謝你的快速回答。我試圖用問題更新來分析我的問題。另一方面,我實際上無法檢查你的想法是否奏效。但事實上一切事情都很好,即使我使用了數組 – pex 2010-10-27 11:49:26

+0

你是什麼意思你不能檢查我的想法是否工作,只需刪除數組括號並上傳:) – s84 2010-10-27 12:10:57

+0

我的意思是它的工作方式相同 - 所以它不對我的問題有影響^^謝謝,雖然! – pex 2010-10-27 14:01:02