Ruby on Rails:当join模型使用belongs_to时,如何通过关联构造has_many

时间:2017-04-28 00:13:32

标签: ruby-on-rails activerecord associations

当连接模型使用belongs_to时,我正在尝试通过关联创建一个has_many。

此处示例:

class User
  has_many :projects, through: :project_memberships
end

class ProjectMembership
  belongs_to :project
end

class Project
  has_many :project_memberships
end

Rails告诉我这种关联无效。如果此处无法使用:through关联,那么使用ActiveRecord访问用户拥有会员资格的所有项目的最佳方式是什么?

1 个答案:

答案 0 :(得分:3)

用户必须与ProjectMembership相关,例如:

class User
  has_many :project_memberships
  has_many :projects, through: :project_memberships
end

class ProjectMembership
  belongs_to :project
  belongs_to :user
end

class Project
  has_many :project_memberships
end

检查here以获取有关关联的更多信息。