当连接模型使用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访问用户拥有会员资格的所有项目的最佳方式是什么?
答案 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以获取有关关联的更多信息。