![](/img/trans.png)
[英]Eager Load Polymorphic has_many :through Associations in ActiveRecord?
[英]ActiveRecord, has_many :through, and Polymorphic Associations
伙計們,
想確保我理解正確。 請忽略繼承的情況(SentientBeing),嘗試着重於has_many中的多態模型:通過關系。 也就是說,考慮以下......
class Widget < ActiveRecord::Base
has_many :widget_groupings
has_many :people, :through => :widget_groupings, :source => :person, :conditions => "widget_groupings.grouper_type = 'Person'"
has_many :aliens, :through => :widget_groupings, :source => :alien, :conditions => "video_groupings.grouper_type = 'Alien'"
end
class Person < ActiveRecord::Base
has_many :widget_groupings, :as => grouper
has_many :widgets, :through => :widget_groupings
end
class Alien < ActiveRecord::Base
has_many :widget_groupings, :as => grouper
has_many :widgets, :through => :widget_groupings
end
class WidgetGrouping < ActiveRecord::Base
belongs_to :widget
belongs_to :grouper, :polymorphic => true
end
在一個完美的世界里,我想,給一個Widget和一個人,做一些像:
widget.people << my_person
但是,當我這樣做時,我注意到'grouper'的'type'在widget_groupings中始終為null。 但是,如果我喜歡以下內容:
widget.widget_groupings << WidgetGrouping.new({:widget => self, :person => my_person})
然后所有的工作正如我通常預期的那樣。 我不認為我曾經見過這種非多態關聯,只是想知道這是否是特定於這個用例的東西,或者我是否有可能盯着一個bug。
謝謝你的幫助!
Rails 3.1.1存在一個已知問題 ,它破壞了這一功能。 如果您遇到此問題首先嘗試升級,則已在3.1.2中修復
你真是太近了 問題是你誤用了:source選項。 :source應該指向多態的belongs_to關系。 然后,您需要做的就是為您嘗試定義的關系指定:source_type。
對Widget模型的此修復應該允許您完成您正在尋找的內容。
class Widget < ActiveRecord::Base
has_many :widget_groupings
has_many :people, :through => :widget_groupings, :source => :grouper, :source_type => 'Person'
has_many :aliens, :through => :widget_groupings, :source => :grouper, :source_type => 'Alien'
end
如上所述,這不適用於rails 3.1.1,因為上面有一個bug:source,但它已在Rails 3.1.2中修復
有很多:通過和多態不一起工作。 如果您嘗試直接訪問它們,則應該拋出錯誤。 如果我沒有弄錯的話,你必須親自編寫widget.people和推送例程。
我不認為這是一個錯誤,它只是尚未實現的東西。 我想我們會在功能中看到它,因為每個人都有一個可以使用它的情況。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.