I have User model and I want to create friendship between users. I've achieved this using has_and_belongs_to_many
has_and_belongs_to_many :friends, class_name: 'User', foreign_key: :friend_id
And I have table for this association:
create_table :users_users do |t|
t.uuid :user_id, null: false
t.uuid :friend_id, null: false
t.timestamps
end
When I get friends via user.friends I need to have association where current user is in user_id column or friend_id. My current solution returns me only records where user is in friend_id table.
I have two solution for this:
- Duplicate records [{user_id: 1, friend_id: 2}, {user_id: 2, friend_id: 1}]
- Override user.friends method and return my custom query
Both solution are not elegant and optimal.
I've read article about it, but the solution from this article is very complicated.
Is there any other solutions for this problem? I'm using rails 5.
The active record way to do this is:
has_many
relation instead ofHABTM
relationusers_users
table to find all records that matchuser_id=my_user.id
orfriend_id=my_user.id
so I suggest putting this method in User model:
UserFriend
model: