簡體   English   中英

Ruby on Rails:當聯接模型使用belongs_to時,如何通過關聯來構造has_many

[英]Ruby on Rails: How to structure a has_many, through association when join model uses a belongs_to

我正在嘗試通過聯接模型使用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來訪問用戶具有成員資格的所有項目的最佳方法是什么?

用戶必須與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

在此處查看有關關聯的更多信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM