2011-02-09 69 views
4

我有一個標準的多態關係,我需要知道它的父母是誰之前,我保存它。如何在保存之前獲得多態對象的父對象?

Class Picture < AR::Base 
    belongs_to :attachable, :polymorphic => true 
end 

Class Person < AR::Base 
    has_many :pictures, :as => :attachable 
end 

Class Vehicle < AR::Base 
    has_many :pictures, :as => :attachable 
end 

我通過上傳回形針的圖片和我建立需要做不同的事情,不同的圖片(即該人的照片應該有寶麗來看看&車輛圖片應該有一個疊加)的處理器。我的問題是,在保存圖片之前,我不知道它是否與人物或車輛相關聯。

我試圖在個人&車輛中放置一個「標記」,以便我可以告訴他們appart,但是當我在回形針處理器中時,我所看到的唯一一件事是Picture類。 (我的下一個想法是爬上堆棧試圖獲得父母的呼叫者,但這看起來對我來說很臭。你會怎麼做?

+1

是`@ picture.attachable`之後你在做什麼?你如何保存圖片? – Zabba 2011-02-09 14:30:01

+1

self.attachable返回什麼? `類圖片 true; before_save:檢查; def check;把self.attachable;結束;結束' – fl00r 2011-02-09 14:32:05

回答

1

我「解決」這個問題,並希望在這裏發佈,以便它可以幫助別人。我的解決方案是創建一個「父」方法圖片類爬上堆棧,發現看起來像父母的東西。

警告:這是蹩腳的代碼,應該不會在任何情況下使用。它適用於我,但我不能保證它不會在路上造成身體傷害。

caller.select {|i| i =~ /controller.rb/}.first.match(/\/.+_controller.rb/).to_s.split("/").last.split("_").first.classify.constantize 

這段代碼確實是走了caller樹尋找一個名爲*_controller.rb祖先。如果它找到一個(它應該),那麼它將該名稱解析爲一個應該是調用代碼的父類的類。

BTW:我放棄了回形針和使用CarrierWave開始。它更容易完成這種事情,我能夠在一半時間內完成它的工作。 Yea CarrierWave!

5

你應該能夠從多態關聯中得到它

Class Picture < AR::Base 
    belongs_to :attachable, :polymorphic => true 

    before_create :apply_filter 

    private 

    def apply_filter 
    case attachable 
    when Person 
     #apply Person filter 
    when Vehicle 
     #apply Vehicle filter 
    end 
    end 
end 

或者,你可以要求它的關聯類型,因此忽略了最低必須建立和比較的對象,而只是做字符串比較。

Class Picture < AR::Base 
    belongs_to :attachable, :polymorphic => true 

    before_create :apply_filter 

    private 

    def apply_filter 
    case attachable_type 
    when "Person" 
     #apply Person filter 
    when "Vehicle" 
     #apply Vehicle filter 
    end 
    end 
end 
0

我創建了一個插值來解決它。我的回形針模型是Asset和Project是父模型。還有其他模型,如項目模型下的文章,可以有附件。

Paperclip.interpolates :attachable_project_id do |attachment, style| 
    attachable = Asset.find(attachment.instance.id).attachable 
    if attachable.is_a?(Project) 
    project_id = attachable.id 
    else 
    project_id = attachable.project.id 
    end 
    return project_id 
end 

Paperclip.interpolates :attachable_class do |attachment, style| 
    Asset.find(attachment.instance.id).attachable.class 
end 

,並用它在像模型:

has_attached_file :data, 
    :path => "private/files/:attachable_project_id/:attachable_class/:id/:style/:basename.:extension", 
    :url => "/projects/:attachable_project_id/:attachable_class/:id/:style", 
    :styles => { :small => "150x150>" }