ruby-on-rails - many - rails foreign key
ActiveRecord, has_many: through, Asociaciones polimórficas con STI (1)
¿Has probado lo más simple? Agregar :conditions al has_many :through s?
En otras palabras, algo como esto (en 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''
JamesDS tiene razón en que se necesita una unión, pero no está escrita aquí, ya que la has_many :through ya lo está haciendo.
En ActiveRecord, has_many: through y Polymorphic Associations , el ejemplo de OP pide ignorar la posible superclase de Alien y Person ( SentientBeing ) . Aquí es donde radica mi pregunta.
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
En este ejemplo modificado, los valores de grouper_type para Alien y Person ahora son almacenados por Rails como SentientBeing (Rails busca la clase base para este valor de grouper_type ) .
¿Cuál es la forma correcta de modificar los has_many en Widget para filtrar por tipo en tal caso? Quiero poder hacer Widget.find(n).people y Widget.find(n).aliens , pero actualmente ambos métodos ( .people y .aliens ) devuelven el conjunto vacío [] porque grouper_type siempre es SentientBeing .