在Rails中,需要在相同的两个模型之间设置多对多关系和一对多关系

时间:2013-03-17 10:09:51

标签: ruby-on-rails activerecord

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

我在模型中设置了以下代码来处理这些关联。请注意,项目的数据库中包含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

如何设置这些模型以便它们按照我的意图工作?

注意:我在 - Two has_many links between the same models之后对我的代码进行了建模,但它没有帮助。

1 个答案:

答案 0 :(得分:0)

您必须在用户和项目模型中拥有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

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

Projects_Users Table
user_id | project_id