我应该如何在 Rails 3.2 中创建以下模型?项目可以有 1+ 个所有者和 1+ 个用户。它们都是 Person 类的实例。我已经考虑过,has_and_belongs_to_many
但我不知道如何为每个项目处理两个单独的 Persons 集合。
问问题
53 次
3 回答
0
您将需要一个连接模型来表示每个has-and-belongs-to-many
关系,并且您可以使用has-many-through
如下所述进行访问:
class ProjectOwnerLink < ActiveRecord::Base
belongs_to :project
belongs_to :owner, class_name: 'Person'
end
class ProjectUserLink < ActiveRecord::Base
belongs_to :project
belongs_to :user, class_name: 'Person'
end
class Project < ActiveRecord::Base
has_many :project_owner_links
has_many :owners, :through => :project_owner_links
has_many :project_user_links
has_many :users, :through => :project_user_links
end
class Person < ActiveRecord::Base
has_many :project_owner_links
has_many :owned_projects, :through => :project_owner_links, :source => :project
has_many :project_user_links
has_many :used_projects, :through => :project_user_links, :source => :project
end
于 2013-05-27T18:40:37.327 回答
0
于 2013-05-27T20:04:48.503 回答
0
您可以定义另一个模型Participation
来保存关系的类型,即用户的角色。(未经测试)代码:
class Project < ActiveRecord::Base
has_many :participations
has_many :users, :through => :participations
def with_role(role)
includes(:participations).where('participation.role = ?', role)
end
def owners
users.with_role('owner')
end
def participants
users.with_role('participant')
end
end
class User < ActiveRecord::Base
has_many :participations
has_many :projects, :through => :participations
def with_role(role)
includes(:participations).where('participation.role = ?', role)
end
def projects_owned
projects.with_role('owner')
end
def projects_participating_in
projects.with_role('participant')
end
end
class Participation < ActiveRecord::Base
# has an attribute 'role'
belongs_to :project
belongs_to :user
end
于 2013-05-27T18:58:24.853 回答