2013-05-27 65 views
0

如何在Rails 3.2中創建以下模型?項目可以有1個以上的所有者和1個以上的用戶。他們都是Person類的實例。我想過has_and_belongs_to_many,但我不知道如何爲每個項目處理兩個單獨的人員集合。在Rails中命名多對多關係

回答

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 
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