Multiple has_many relationships to same model

后端 未结 4 2009
抹茶落季
抹茶落季 2021-02-04 09:07

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 boo

4条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-04 09:15

    Maybe something like this?

    User
      has_many :bookmarks
      has_many :posts, through: :bookmarks
      has_many :authored_posts, foreign_key: :author_id, class_name: 'Post'
    Bookmark
      belongs_to :post
      belongs_to :user
    Post
      belongs_to :author, class_name: 'User'
      has_many :bookmarks
      has_many :users, through: :bookmarks
    

    In this way, you are able to keep posts that are written by and bookmarked by a user separate. You could also set it up so that whenever an author creates a post, it can automatically get bookmarked by the user. i.e.

    class PostsController < ActionController::Base
      def create
        @post = @user.authored_posts.build(post_params)
        @user.posts << @post
    
        if @post.valid?
          # do good stuff
        else
          # do errors
        end
      end
    end
    

    There is a strong 1:N relationship between author and authored_posts. Then there is a weaker N:M relationship between Users and Posts using Bookmark as the join model. You can add authored posts to be bookmarked when they are created using the controller code above. Removing a bookmark on an authored post will simply remove it from the posts relationship, but not the authored_posts relationship.

    You cannot define multiple relationships using the same name.

提交回复
热议问题