Antoine M.
Antoine M.

Reputation: 3691

Ruby on rails : associations with multiple columns on non id key

I try to implement a simple app where I have users and I get the users friendships from a social network. I have two models with the following columns:

User :

FriendsRelation :

How to implement the associations?

for now I wrote on users :

has_many :friends1, :class_name =>"FriendsRelation", :foreign_key =>"user1_sn_id"
has_many :friends2, :class_name =>"FriendsRelation", :foreign_key =>"user2_sn_id"

The problem is that if I want to get all the friends of a user, I have to use u.friends1 and u.friends2 but how do I get rid of the dissymetry?

And what associations should I put on FriendsRelation?

Also, the user ids in the FriendsRelation table are those from the social network because it is easier for me. Is it a problem? Should I put the user id instead?

Upvotes: 0

Views: 293

Answers (1)

Matzi
Matzi

Reputation: 13925

Using your own id instead of the primery key is not a problem. Only make sure that there are no duplications and add an index to that column as well.

Regarding the dissimetry you have multiple solutions:

  • Merging the two list based on the two ids e.g. def friends; friends1 + friends2; end
  • Adding double records (both ways) to the friends table
  • Specifying custom scopes for the relations to reflect the relationship from the right point of view

All have pros and cons, but all are valid solutions AFAIK.

Upvotes: 1

Related Questions