Reputation: 1160
I'm trying to test out a Facebook-style friend system. I have a simple User model and a UserRelationship model that takes two foreign keys from the users table, which I've named inviter_id
and invited_id
:
class User < ApplicationRecord
has_many :user_relationships
has_many :friends, through: :user_relationships, source: :invited
end
class UserRelationship < ApplicationRecord
belongs_to :inviter, class_name: "User"
belongs_to :invited, class_name: "User"
end
I've tried variations of this and I can't figure out where I'm going wrong. I want to be able to call User.first.friends
and get a full friends list. currently the error I'm getting is:
ActiveRecord::StatementInvalid: PG::UndefinedColumn: ERROR: column user_relationships.user_id does not exist
The tables:
create_table "user_relationships", force: :cascade do |t|
t.integer "inviter_id"
t.integer "invited_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "users", force: :cascade do |t|
t.string "name"
t.string "email"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
Thanks
UPDATE
Using what Abhilash said about the has_many :user_relationships
association I changed it to this:
class User < ApplicationRecord
has_many :user_relationships, foreign_key: "invited_id"
has_many :friends, through: :user_relationships, source: :invited
end
The problem is that that only returns the inviteds, not the inviters. I feel like there should be a way to get both using the database and associations?
Upvotes: 0
Views: 29
Reputation: 1549
You need to remove the below line from the User
model.
has_many :user_relationships
Because in the UserRelationship
model you've fields for inviter_id
and invited_id
but not user_id
.
So you can have a method like this in your model to get user_relationships
for a given user.
def user_relationships
UserRelationship.where("invited_id = ? OR inviter_id = ?", self.id, self.id)
end
Edited:
You can also have associations like below:
class User < ActiveRecord::Base
has_many :inviter_user_relationships, :class_name => 'UserRelationship', :foreign_key => 'inviter_id'
has_many :invited_user_relationships, :class_name => 'UserRelationship', :foreign_key => 'invited_id'
def user_relationships
inviter_user_relationships + invited_user_relationships
end
end
Upvotes: 1