民間,想要確保我正確理解了這一點。并且請忽略此處的繼承情況(SentientBeing),而嘗試著重于has_many:through關系中的多態模型。也就是說,請考慮以下事項...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'"endclass Person < ActiveRecord::Base has_many :widget_groupings, :as => grouper has_many :widgets, :through => :widget_groupingsendclass Alien < ActiveRecord::Base has_many :widget_groupings, :as => grouper has_many :widgets, :through => :widget_groupings endclass WidgetGrouping < ActiveRecord::Base belongs_to :widget belongs_to :grouper, :polymorphic => trueend在一個完美的世界中,我想給一個小部件和一個Person,執行以下操作:widget.people << my_person但是,當我這樣做時,我注意到widget_groupings中“分組器”的“類型”始終為空。但是,如果我執行以下操作:widget.widget_groupings << WidgetGrouping.new({:widget => self, :person => my_person}) 然后所有的工作都像我通常期望的那樣。我認為我從未見過這種情況發生在非多態關聯中,只是想知道這是否是該用例所特有的,或者我是否有可能盯著一個錯誤。謝謝你的幫助!
3 回答

慕村9548890
TA貢獻1884條經驗 獲得超4個贊
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

慕神8447489
TA貢獻1780條經驗 獲得超1個贊
有很多:through和多態不能一起使用。如果您嘗試直接訪問它們,它將引發錯誤。如果我沒記錯的話,您必須手寫widget.people和push例程。
我不認為這是一個錯誤,只是還沒有實現。我想我們會在功能中看到它,因為每個人都有可以使用它的情況。
- 3 回答
- 0 關注
- 629 瀏覽
添加回答
舉報
0/150
提交
取消