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
關係?
移出這個項目,所以我沒有測試這個答案,但它看起來很合理。擁有中介結構(描繪)以支持「一對一」關係有一些「嗅覺」,並不是我所期待的,但是你的方法經過深思熟慮並且似乎可行。如果我在不久的將來回到這個問題,我會測試一下。 –
你是對的,加入一對一關係表並不好,但它是最簡單的方法。 好的解決方案是像'線程',模型(員工或產品)將屬於線程和模型的線程必須有約束(圖像計數 - 1,2或無窮大) –