【发布时间】:2010-04-14 22:17:28
【问题描述】:
在我的应用中,我有一个用户模型和一个项目模型。一个用户有_许多任务,每个项目都属于_一个用户。但是随着每个项目都有一个所有者,创建它的用户,我希望所有者能够与其他人共享它(以便该项目与他们自己的帐户一起显示在其他用户的帐户上)。我想必须使用 has_many :through,并设置一个带有 user_id 和 project_id 的 projects_users 表。我猜这将是最终结果?
Project.first.user
# The creator of the project
=> #<User id: 1, name: 'andrew', etc...>
Project.first.users
# The users that the creator chose to share it with
=> [#<User id: 2 ...>, #<User id: 3 ...>]
我一直在研究这个问题,并创建了一个带有 user_id 和 project_id 列的 SharedProject 模型:
class SharedProject < ActiveRecord::Base
belongs_to :user
belongs_to :project
end
我想同时调用 user.projects 和 user.shared_projects,但我不知道如何让 shared_projects 返回项目记录而不是 shared_projects 表中的记录。我不能做has_many :projects, :through => :shared_projects 从那以后我将无法返回用户创建的项目。
class User < ActiveRecord::Base
has_many :projects # Calling user.projects returns the projects that user created
has_many :shared_projects # How to get user.shared_projects to return project records?
end
【问题讨论】:
标签: ruby-on-rails model associations