Search code examples
ruby-on-railsmodels

Model User has many posts and can create post


Hello i have trouble with logic. In my app users can create Posts and add them to favourites. The problem is in assiciations on Posts and Users. When User creates Post user_id is applied to posts table. How can i make associations when other user or this one add Post to favourite.


Solution

  • You need to create another table that will join a post and user. You can call that table favorites with 2 columns: post_id and user_id

    class Favorite < ActiveRecord::Base
      belongs_to :post
      belongs_to :user
    end
    
    class User < ActiveRecord::Base
      has_many :posts
      has_many :favorites
      has_many :favorite_posts, through: :favorites, source: :post
    end
    
    class Post < ActiveRecord::Base
      belongs_to :user
      has_many :favorites
      has_many :favorited_by_users, through: :favorites, source: :user
    end