ActiveRecord, has_many: through, Polymorphic Associations with STI

În ActiveRecord, has_many: through,și Polymorphic Associations , exemplul OP solicită ignorarea posibilei superclase a Alien și Person ( SentientBeing ) . Aici se află întrebarea mea.

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

În acest exemplu modificat, valoarea grouper_type pentru Alien și Person sunt acum ambele stocate de Rails ca SentientBeing (Rails caută clasa de bază pentru această valoare grouper_type ) .

Care este modalitatea corectă de a modifica has_many în Widget pentru a filtra după tip într-un astfel de caz? Vreau să pot face Widget.find (n) .people și Widget.find (n) .aliens , dar în prezent ambele metode ( .people și .aliens ) returnează setul gol [] pentru că grouper_type este întotdeauna SentientBeing .

9
задан Community 23 May 2017 в 12:02
поделиться