dee*_*our 9 ruby-on-rails ruby-on-rails-3
在ActiveRecord,has_many:through和Polymorphic Associations中,OP的示例请求忽略可能的超类Alien和Person (SentientBeing).这是我的问题所在.
class Widget < ActiveRecord::Base
has_many :widget_groupings
has_many :people, :through => :widget_groupings, :source => :person, :source_type => 'Person'
has_many :aliens, :through => :widget_groupings, :source => :alien, :source_type => 'Alien'
end
SentientBeing < ActiveRecord::Base
has_many :widget_groupings, :as => grouper
has_many :widgets, :through => :widget_groupings
end
class Person < SentientBeing
end
class Alien < SentientBeing
end
Run Code Online (Sandbox Code Playgroud)
在这个修改过的例子中grouper_type,Alien和的值Person现在都被Rails存储为SentientBeing (Rails为这个grouper_type值寻找基类).
在这种情况下,修改has_many's in Widget以按类型过滤的正确方法是什么?我希望能够做的Widget.find(n).people和Widget.find(n).aliens,但目前这些方法都(.people和.aliens)返回空集[],因为grouper_type始终SentientBeing.
小智 13
你有没有尝试过最简单的东西 - 添加:conditions到has_many :throughs?
换句话说,像这样(在widget.rb中):
has_many :people, :through => :widget_groupings, :conditions => { :type => 'Person' }, :source => :grouper, :source_type => 'SentientBeing'
has_many :aliens, :through => :widget_groupings, :conditions => { :type => 'Alien' }, :source => :grouper, :source_type => 'SentientBeing'
Run Code Online (Sandbox Code Playgroud)
JamesDS是正确的,需要一个连接 - 但它没有写在这里,因为has_many :through关联已经在做了.
| 归档时间: |
|
| 查看次数: |
4220 次 |
| 最近记录: |