相关疑难解决方法(0)

ActiveRecord,has_many:through和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
Run Code Online (Sandbox Code Playgroud)

在一个完美的世界里,我想,给一个Widget和一个人,做一些像:

widget.people << …
Run Code Online (Sandbox Code Playgroud)

activerecord ruby-on-rails polymorphic-associations

115
推荐指数
1
解决办法
2万
查看次数