On Wednesday, July 20, 2011 7:04:09 AM UTC-6, Jedrin wrote:
then they all have to share the same fields in one record). I figure
there must be some way to do this with a kind of intermediate join or
something, but I haven’t seen any examples that I can recall …
If I understand what you’re saying then no, it isn’t even possible using
a
join table. This is the quick example I tested with:
The following demonstrates that this DOES NOT work…
class Region < ActiveRecord::Base
a.k.a the “parent” that wants to “own” several
different kinds of children through one relation (shapes)
has_many :regions_shapes
has_many :shapes, :through => :regions_shapes
end
class RegionsShape < ActiveRecord::Base
polymorphic join model
belongs_to :region
belongs_to :shape, :polymorphic => true
end
class Ellipse < ActiveRecord::Base
one of two types of “children” that can belong to a
Region (parent) through its “shapes” relation
has_one :regions_shape, :as => :shape
has_one :region, :through => :regions_shape
end
class Polygon < ActiveRecord::Base
the other of the two types of “children”
has_one :regions_shape, :as => :shape
has_one :region, :through => :regions_shape
end
All of the relationships work fine EXCEPT for the one you wanted, in
this
example Region#shapes. Trying to use it will raise:
ActiveRecord::HasManyThroughAssociationPolymorphicError: Cannot have a
has_many :through association ‘Region#shapes’ on the polymorphic object
‘Shape#shape’
I think you’d have to simply have several explicit relationships for
each
type that the parent can “have”:
class Region < ActiveRecord::Base
has_many :ellipses
has_many :polygons
end
class Polygon < ActiveRecord::Base
belongs_to :region
end
class Ellipse < ActiveRecord::Base
belongs_to :region
end
Then just create a “combining” method for each relation-like action that
the
various relation methods support. Since you aren’t working with actual
relation objects, you can’t chain or further filter on the results
though
so…
def shapes
polygons + ellipses # or something like that for an Array (not a
relation)
end
I’m assuming this is because if #shapes could be/return a relation
then
said relation would really have to have the ability to map to n
seperate
SQL select statements (one for each table that can possibly be a
“child”).
As such, further filtering/sorting/offset/limit operations on such a
relation would be hard, not make sense, or be impossible.
Anyone more knowledgeable know if I’m wrong here?