Reputation: 2107
I have a doubt, Im making a friend's platform on a Ruby on Rails site; I have a table called users, and a table called friends that manages the friendships between the users. In friends I have 2 fields, *user_id1* and *user_id2*. This is the relationship I made in the models:
class User < ActiveRecord::Base has_many :friends end
class Friend < ActiveRecord::Base belongs_to :user, :foreign_key => "user_id1" belongs_to :user, :foreign_key => "user_id2" end
Is this a good way to handle this situation? Another idea is create another model that points to the same table in the database, userAux, and use it for the relationship. What do you think is best? Do you have a better idea?
Thanks in advance.
Upvotes: 0
Views: 360
Reputation: 33698
A self-referencing many-to-many structure is often called a Bill of Materials. It is a very good idea, and quite commonly used in Relational databases. Here is the Data Model. You would have boolean attributes such as IsAccepted
and IsRejected
.
Please do not name the columns as user_id1, 2
. Please call them something that is actually meaningful, such host_id
and guest_id
or requester_id
and friend_id
. The relevance of that will only become clear when you are coding.
Readers who are unfamiliar with the Relational Modelling Standard may find IDEFIX Notation useful.
Upvotes: 4
Reputation: 15056
There is actually a very similar situation referenced here: http://oldwiki.rubyonrails.org/rails/pages/HowToCreateASelfReferentialManyToManyRelationship
Upvotes: 1