Reputation: 851
I'm trying to get a join table working with a custom id in the schema. I want to be able to get all the relevant posts for a user through the join table using the custom_id on the join table as recipient_id
Here is my current setup:
class User > ActiveRecord::Base
has_many :user_posts
has_many :received_posts, through: :user_posts, source: :recipient
end
class UserPost < ActiveRecord::Base
belongs_to :recipient, class_name: "User"
belongs_to :post
end
class Post < ActiveRecord::Base
has_many :user_posts
has_many :recipients, through: :user_posts, source: :recipient
end
Here's the schema of my join table:
UserPost
recipient_id: integer
post_id: integer
The error I get is:
PG::UndefinedColumn: ERROR: column user_posts.user_id does not exist
I've tried adding the source like above but to no avail. It makes me think that it's looking for the user_id and not recipient_id on the join table. I'm not sure how to correctly specify the custom id as the field to use. I've tried foreign keys and other answers on here but to no luck. Could be that I'm implementing foreign keys or source wrong.
Any help is much appreciated, Thanks.
Upvotes: 1
Views: 1066
Reputation: 1953
In User model, add foreigh_key
to :user_posts
class User > ActiveRecord::Base
has_many :user_posts, foreign_key: :recipient_id
has_many :received_posts, through: :user_posts, source: :recipient
end
Upvotes: 2