A site about Linux, coding in general, and things I've figured out. Add the occasional rant, musings on the world, and visions of the future. Stir, and sip lightly.
Random header image... Refresh for more!

Bi-directional relationships in Rails

Really that should be “Bi-directional self-referential relationships in ActiveRecord models”, but that’s just too much to say!

A common example for this would be if you had a Person model and a Friendship model, and you wish the friendship between two people to be a two-way road, like on Facebook. The project I’m working on is a genealogy application that has partnerships (eg. marriage) between two people, but it’s the same deal.

Now typically, :has_many relationships in ActiveRecord are uni-directional. You have to do a little bit of trickery to get it to happen both ways. Here’s the code.

[Read more →]

January 3, 2011   No Comments