0

我有一个用户模型

class User < ActiveRecord::Base
  has_many :projects
end

我有一个项目模型

class Project < ActiveRecord::Base
  belongs_to :user
end

显然,现在每个项目都归一个用户所有,每个项目只能有一个用户。我现在想让我的模型代表两个模型之间的另一种关系。我希望用户能够关注多个项目,无论谁拥有该项目。我知道我将不得不使用 has_many :through 并创建一个连接,但我无法解决如何更改模型以保持我当前的关系并添加新的关系。

4

2 回答 2

1

Well, in that case, in your show/index action display all the projects (Project.all) in your project table. This way all users have access to all the projects. Now, in your edit action, use user.projects.all to display projects of that particular user. That should solve your problem, I don't see the need of any further association here.

Update:
This should suffice:

class Project < ActiveRecord::Base
belongs_to :user

class User < ActiveRecord::Base
has_many :projects_followed, :through => :projects
user has_many :projects_owned, :through => :projects

If you don't wish to create two more relations, create just one:
class ProjectsSubscribed
belongs_to :project
with three fields: project_id, is_owned, is_followed

于 2012-05-17T10:30:18.413 回答
0

尝试以下关系。

class User < ActiveRecord::Base
  has_many :followers
  has_many :projects, :through => :followers
end

class Follower < ActiveRecord::Base
  belongs_to :user
  belongs_to :project
end

class Project < ActiveRecord::Base
  has_many :followers
  has_many :users, :through => :followers
end

请注意:如果您需要将关系模型作为独立实体使用,则可以使用has_many :through关系。如果您不需要对关系模型做任何事情,那么设置 has_and_belongs_to_many 关系可能会更简单。

希望它是有帮助的。

于 2012-05-17T11:02:04.967 回答