1

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.

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot! worked perfectly. I'd been adding the foreign key to the has_many through association.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.