Matthew Shapiro wrote:
Marnen Laibow-Koser wrote:
I am having trouble figuring out how to set this up as a Model though,
especially since you can't always know if the object you are looking at
is object1 or object2 in the relationship field.Does anyone have any advice for this type of problem?
Are the associations one-way or two-way? In other words, if ObjA is
related to ObjB, is ObjB automatically related to ObjA?It is two-way (If A is related to B, B is also automatically related to
A)
So you have an arbitrary graph. Normally I'd say that you just want to
do the object1_id and object2_id stuff you already thought of, and just
sort the two objects unambiguously. But that won't really give you the
ability to do @myobject.show_all_related_objects without looking for it
in both object1 and object2. Two ideas come to mind:
1 (probably less good). Create relationship records in both orders:
object1_id | object2_id |
1 | 2 |
2 | 1 |
Of course, this stores everything twice, with all attendant problems.
2 (probably the better idea). A bit more complex, but easier to
traverse. You may need the nested_has_many_through plugin (or
:finder_sql) for this to work correctly.
class NodeMembership < AR::B # join model since Rails won't do
polymorphic habtm
belongs_to :node, :polymorphic => true
belongs_to :relationship
end
class Relationship < AR::B
has_many :node_memberships
has_many :nodes, :through => :node_memberships # may also need
:polymorphic => true -- not sure
end
class Model[A,B,C...] < AR::B
# you will probably want to refactor this into an abstract base class
has_many :node_memberships, :as => :node
has_many :relationships, :through => :node_memberships
end
Then, to find all relationships that a model participates in, you can
just do @model_a.relationships, which will translate into something like
SELECT r.*
FROM node_memberships nm LEFT JOIN relationships r ON (r.id =
nm.relationship_id)
WHERE nm.node_id = #{@model_a.id} AND nm.node_type = 'ModelA'
I hope that's clear...
Best,