Noam B.
Noam B.

Reputation: 3250

Rails - association with another table

I have a users table(and a user model). In my scenario, a user can have multiple identities. I.e. user michael1 (id = 1) can be connected to michael2 (id = 2) and michael3 (id = 3).

I created a table to store these connections. I called it user_relations and it has: id, user_id, related_user_id columns. In the previous example I'll have:

user_id | related_user_id

1 | 2

1 | 3

In users model I defined: has_many :user_relations, and in user_relation I defined: belongs_to :users.

Now, I want that when I have a user object I would be able to get:

current_user.user_relations - and get all users objects that are connected according to the table. In previous example, if I have current_user as user with id 1, I would like to get users with id 2 and 3.

How can I achieve that?

BTW - I have an id because I saw that without it, I am not able to use destroy_all. If anyone has an insight regarding this also, I am open to hear.

Upvotes: 0

Views: 156

Answers (1)

davidrac
davidrac

Reputation: 10738

I think this should work. If I missed something you can look here for details:

class User < ActiveRecord::Base
  has_many :user_relations
  has_many :related_users, :through=> :user_relations
end

class UserRelations< ActiveRecord::Base
  belongs_to :user, :class_name => "User", :foreign_key => "user_id"
  belongs_to :related_user, :class_name => "User", :foreign_key => "related_user_id"
end

Upvotes: 1

Related Questions