我有一个应用程序,其中项目属于一个所有者(用户)并且拥有并属于许多成员(用户)。
我在模型中设置了以下代码来处理这些关联。请注意,项目在其数据库中有 owner_id 但没有 member_id
项目模型代码
attr_accessible :description, :name, :owner_id, :avatar_url
belongs_to :owner, foreign_key: :owner_id, class_name: "User"
has_and_belongs_to_many :members, class_name: "User"
用户型号代码
has_and_belongs_to_many :projects
has_many :owned_projects, class_name: "Project", foreign_key: "owner_id"
has_many :associated_projects, class_name: "Project", foreign_key: "member_id"
在给定的项目中,我可以调用 p.owner 但不能调用 p.members。对于用户,我可以调用 u.owned_projects 或 u.projects,但不能调用 u.associated_projects。
当我尝试这些命令时,我收到以下错误
1.9.3p194 :003 > p.members
User Load (0.2ms) SELECT "users".* FROM "users" INNER JOIN "projects_users" ON "users"."id" = "projects_users"."user_id" WHERE "projects_users"."project_id" = 3
ActiveRecord::StatementInvalid: SQLite3::SQLException: no such table: projects_users: SELECT "users".* FROM "users" INNER JOIN "projects_users" ON "users"."id" = "projects_users"."user_id" WHERE "projects_users"."project_id" = 3
和
1.9.3p194 :007 > ryan.associated_projects
Project Load (0.2ms) SELECT "projects".* FROM "projects" WHERE "projects"."member_id" = 14593
ActiveRecord::StatementInvalid: SQLite3::SQLException: no such column: projects.member_id: SELECT "projects".* FROM "projects" WHERE "projects"."member_id" = 14593
如何设置这些模型,以便它们按我的意愿工作?
注意:我在之后建模了我的代码 -相同模型之间的两个 has_many 链接,但它没有帮助。