Alexander Isora
Alexander Isora

Reputation: 35

Additional relation between records in Rails 5.0

I need your small advice help.

I have trivial models: Post and User. A user has_many :posts and a post belongs_to :user. A post has one owner.

I need somehow add an additional relation: a post can have multiple contributors. A contributor is a user too. I need to be able to write something like this: @post.contributors (shows User records) and @user.contributed_to (shows Post records).

How do I do that?

Upvotes: 0

Views: 40

Answers (1)

Igor Drozdov
Igor Drozdov

Reputation: 15045

You'll need many-to-many association here, because user has_many posts and posts has_many users.

To implement it, you need to create an additional model (for example, contribution with user_id and post_id columns)

class Contribution < ApplicationRecord
  belongs_to :user
  belongs_to :post
end

And your Post and User classes will contain something like this:

class Post
  belongs_to :user
  has_many :contributions
  has_many :contributors, through: :contributions, source: :user
end

class User
  has_many :posts
  has_many :contributions
  has_many :contributed_posts, through: :contributions, source: :post
end

Upvotes: 1

Related Questions