Rails 5.0 中记录之间的附加关系

Additional relation between records in Rails 5.0

我需要你的小建议帮助。

我有一些简单的模型:PostUser。 一个用户 has_many :posts 和一个 post belongs_to :user。 post 有一个所有者。

我需要以某种方式添加一个附加关系:一个 post 可以有多个贡献者。贡献者也是用户。我需要能够写这样的东西:@post.contributors(显示用户记录)和 @user.contributed_to(显示 Post 记录)。

我该怎么做?

这里你需要多对多关联,因为user has_many postsposts has_many users

要实现它,您需要创建一个额外的模型(例如,contribution 具有 user_idpost_id 列)

class Contribution < ApplicationRecord
  belongs_to :user
  belongs_to :post
end

而您的 PostUser 类 将包含如下内容:

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