user1625602
user1625602

Reputation: 63

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.

Upvotes: 1

Views: 2201

Answers (2)

jvnill
jvnill

Reputation: 29599

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

Upvotes: 2

SG 86
SG 86

Reputation: 7078

You could create an new model/table for association. I would take a many to many relation for this.

Table: Bookmark

user_id | post_id

How a has many :through relationship in rails work is discriped here:

http://guides.rubyonrails.org/association_basics.html#the-has_many-through-association

Upvotes: -1

Related Questions