Creating a "friends" association?

Hi, I have a Friend model that looks like this:

  create_table "friendships", :force => true do |t|     t.column "sent_by_user_id", :integer     t.column "received_by_user_id", :integer     t.column "status", :boolean   end

I would like to be able to define a :friends association in my user model that returns friendships that are both sent_by and received_by a given user. Any way to do this?

I've been told that traditionally you just create two friendship records to handle this, but it seems like a cumbersome solution.

Thanks,

Andrew

That's the canonical solution if it's OK for the amount of data, otherwise you need to emulate symmetry by hand:

   sender.friends    receiver.friends

should contain each other and the nice way to do that is to delegate in AR. That symmetry is then maintained by callbacks on the join model.

Additionally, you normally want to apply transitive somehow and the SQL is easier if you have a "direction" to follow, I wrote a little about this here:

   Advogato: Implementation of a network of contacts

-- fxn

[I sent this a few hours ago but have not receive it back, please excuse if you got it twice.]

Hi, I have a Friend model that looks like this:

  create_table "friendships", :force => true do |t|     t.column "sent_by_user_id", :integer     t.column "received_by_user_id", :integer     t.column "status", :boolean   end

I would like to be able to define a :friends association in my user model that returns friendships that are both sent_by and received_by a given user. Any way to do this?

I've been told that traditionally you just create two friendship records to handle this, but it seems like a cumbersome solution.

That's the canonical solution if it's OK for the amount of data, otherwise you need to emulate symmetry by hand:

   sender.friends    receiver.friends

should contain each other and the nice way to do that is to delegate in AR. That symmetry is then maintained by callbacks on the join model.

Additionally, you normally want to apply transitive somehow and the SQL is easier if you have a "direction" to follow, I wrote a little about this here:

   http://www.advogato.org/article/914.html

-- fxn