我应该如何在Rails 3.2中创建以下模型?项目可以有1个以上的所有者和1个以上的用户。它们都是Person类的实例。我考虑过has_and_belongs_to_many
,但我不知道如何为每个项目处理两个单独的人员集合。
答案 0 :(得分:0)
您需要一个联接模型来表示每个has-and-belongs-to-many
关系,并且您将使用here所述的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
答案 1 :(得分: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
答案 2 :(得分:0)