1

我有一个应用程序,其中项目属于一个所有者(用户)并且拥有并属于许多成员(用户)。

我在模型中设置了以下代码来处理这些关联。请注意,项目在其数据库中有 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 链接,但它没有帮助。

4

1 回答 1

0

您的 User 和 Project 模型中必须有 has_many_and_belongs_to 关系。您还需要一个中间表。http://guides.rubyonrails.org/association_basics.html#the-has_and_belongs_to_many-association

Class Project < ActiveRecord::Base

     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"

end

Class User < ActiveRecord::Base

     has_and_belongs_to_many :projects
     has_many :owned_projects, class_name: "Project", foreign_key: "owner_id"

end

如前所述,您必须在成员项目和用户(成员)之间有一个中间表。当您尝试查看项目成员时出现该错误:没有这样的表:projects_users

Projects_Users Table
user_id | project_id
于 2013-03-17T10:54:26.423 回答