2014-01-11 36 views
0

下面是模型/從Rails的指南例如在多態性關係:Rails的多態的關係 - 需要同時使用的has_many和HAS_ONE

class Picture < ActiveRecord::Base 
    belongs_to :imageable, :polymorphic => true 
end 

class Employee < ActiveRecord::Base 
    has_many :pictures, :as => :imageable 
end 

class Product < ActiveRecord::Base 
    has_many :pictures, :as => :imageable 
end 

在我的情況有許多Pictures一個Product是好的,但我不t想要Employee永遠有多個Picture。我想Employee模式是:

class Employee < ActiveRecord::Base 
    has_one :picture, :as => :imageable 
end 

這將允許我使用@employee.picture而非@employee.pictures.first(使用@ employee.pictures.first剛剛有點臭不可聞它的 - 是不是代表真正意圖的關係)。

是否支持has_one ____ :as => :imageable關係?

回答

0

首先,您必須創建一個連接表(類似於圖片)。然後,你將有下一個模型圖片:

class Picture < ActiveRecord::Base 
    has_many :picturing, :dependent => :destroy 
end 

class Picturing < ActiveRecord::Base 
    belongs_to :picture 
    belongs_to :picturable, polymorphic: true 
end 

產品型號:

class Product < ActiveRecord::Base 
    # Many pictures 
    has_many :picturing, as: :picturable 
end 

員工型號:

class Employee < ActiveRecord::Base 
    has_one :picturing, as: :picturable 
    has_one :picture, through: :picturing 
end 
+0

移出這個項目,所以我沒有測試這個答案,但它看起來很合理。擁有中介結構(描繪)以支持「一對一」關係有一些「嗅覺」,並不是我所期待的,但是你的方法經過深思熟慮並且似乎可行。如果我在不久的將來回到這個問題,我會測試一下。 –

+1

你是對的,加入一對一關係表並不好,但它是最簡單的方法。 好的解決方案是像'線程',模型(員工或產品)將屬於線程和模型的線程必須有約束(圖像計數 - 1,2或無窮大) –