Search code examples
ruby-on-railsactiverecord

Multiple has_many relationships to same model


I have a model User that can create Posts

User
 has_many :posts
Post
 belongs_to :user

However, I want to also allow users to save posts as bookmarks. So I added the following:

Bookmark
 belongs_to :post
 belongs_to :user
User
 has_many :posts
 has_many :posts, :through => :bookmarks
Post
 belongs_to :user
 has_many :posts, :through => :bookmarks

This can't be right because it is now ambiguous when I do @user.posts . Does that refer to the posts the user wrote or the posts the user bookmarked?

How do you get around this problem?


Solution

  • How do you get around this problem?

    By giving your associations unique names. It's not that you can't unambiguously access them, it's that your second one is destroying the first one.

    Instead of calling both posts, use bookmarked_posts for your second association and use source: to call posts

    has_many :bookmarked_posts, through: :bookmarks, source: :post