2012-03-01 1 views
0

完成したコーディングプロジェクト、開発者、およびそのロールのデータベースを作成したいとします。属性をレールにhas_and_belongs_to_many関係で定義する

モデルは次のようになります。developers_projectsテーブルは次のようになり

project has_and_belongs_to_many developers 
developers has_and_belongs_to_many projects 

int: developer_id, project_id 
string: role 

は私が

として、それぞれのIDと名前で3つの開発者と2つのプロジェクトを持って一日をします
1, Ashley 
2, Bob 
3, Charles 

1, Tic Tac Toe 
2, Snake 

実際の役割は

Project 1: 
- Manager: Ashley 
- Coder: Bob, Charles 

Project 2: 
- Manager: Charles 
- Coder: Ashley 

プロジェクトの下でマネージャとコーダオブジェクトを定義することは可能ですか?以下のような

class Project < ActiveRecord::Base 
    has_and_belongs_to_many :developers 
    has_and_belongs_to_many :managers, :class_name => "developers", :condition => "role = 'manager'" 
    has_and_belongs_to_many :coders, :class_name => "developers", :condition => "role = 'coder'" 
end 

(これは動作しません)

答えて

2

has_and_belongs_to_manyモデルを宣言せずにテーブルを結合作成することができ、事前にありがとうございます。限り、あなたがこの表の属性を持つようにしたいとあなたは別のモデルを作成する必要があり、例えば、あなたのケースでProjectRoles:

class ProjectRole < ActiveRecord::Base 
    belongs_to :developer 
    belongs_to :project 

    attr_accessible :role 
end 

class Project < ActiveRecord::Base 
    has_many :manager_roles, :class_name => "ProjectRole", 
          :conditions => { :role => 'manager' } 
    has_many :managers, :through => manager_roles 
end 

class Developer < ActiveRecord::Base 
    has_many :project_roles 
    has_many :projects, :through => project_roles 
end 
+0

は私がDeveloper.find(1).projectsを試してみましたが、それは私に初期化されていない一定の開発を提供します::プロジェクト。 Developer.find(1).project_rolesは正しく返しますが、 – rickypai

+0

実際には、私はプロジェクトのbelongs_toが、ロールなしで定義されるべきであることを認識しました。編集と受け入れ。ありがとうございました! – rickypai

+0

@shiroin:はい!私たちは私たちの、あるいは他のいくつかの間違いについて学びます:) – Voldy

関連する問題