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.


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

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"

Need Your Help

What does “Sized is not implemented” mean?


I wrote the following code in Rust:

Can't set IOS 7 simulator home background image

ios-simulator xcode5

I am using IOS7 simulator. I have an image in "Photos". I set it as background image (from "Photos") but home screen background remains black. Can you give me some advice? Thanks in advance. Is an...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.