伙计们,
想确保我理解正确.请忽略继承的情况(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
Run Code Online (Sandbox Code Playgroud)
在一个完美的世界里,我想,给一个Widget和一个人,做一些像:
widget.people << …Run Code Online (Sandbox Code Playgroud) 我从外部API中提取一些数据,并希望在本地缓存结果.我有一个class SearchTerm,我希望通过表格与几个不同的ActiveRecord类型相关联searchable_items.我很确定我的表格设置正确,但我的关联中的某些内容一定是错的.
class Foo < ActiveRecord::Base
has_many :search_terms, :as => :searchable, :through => :searchable_items
end
class Bar < ActiveRecord::Base
has_many :search_terms, :as => :searchable, :through => :searchable_items
end
class SearchTerm < ActiveRecord::Base
has_many :searchables, :through => :searchable_items
end
class SearchableItem < ActiveRecord::Base
belongs_to :search_term
belongs_to :searchable, :polymorphic => true
end
Run Code Online (Sandbox Code Playgroud)
我希望能够做类似的事情SearchTerm.find_by_term('SearchTerm').searchables(它会返回一个Foo和Bar对象的数组)然而,我得到了错误
Could not find the association :searchable_items in model SearchTerm
提前感谢您提供给我的任何见解!