2011-03-30 72 views
1

我有以下的許多一對多的關係:Rails多對多:通過類屬性合併?

class Assignment < ActiveRecord::Base 
    belongs_to :programmer 
    belongs_to :project 
end 

class Programmer < ActiveRecord::Base 
    has_many :assignments 
    has_many :projects, :through => :assignments 
end 

class Project < ActiveRecord::Base 
    has_many :assignments 
    has_many :programmers, :through => :assignments 
end 

在我的分貝:遷移我有以下幾點:

class CreateAssignments < ActiveRecord::Migration 
    def self.up 
    create_table :assignments do |t| 
     t.integer :programmer_id 
     t.integer :project_id 
     t.boolean :owner, :default => false 
     t.timestamps 
    end 
    end 

def self.down 
    drop_table :assignments 
end 
end 

這意味着我可以加載屬於程序員項目,這樣做:

@my_programmer.projects.find params[:id] 

但是,如果你看到我的遷移,每個分配也有一個「所有者」標誌,表示程序員是否是的主人項目。我的問題是這個查詢只會給我這個項目,而不能訪問「所有者」標誌。

那麼如何知道程序員是否是所有者呢?我可以通過另一個電話來獲得協作,但它似乎很愚蠢,因爲它已經在分配上進行JOIN了?

有沒有辦法獲得:through類的屬性,而無需執行特定的數據庫調用?

回答

0

這是相當奇怪的數據庫體系結構。不過你可以試試這個

class Programmer < ActiveRecord::Base 
    has_many :assignments 
    has_many :projects, :through => :assignments 

    def own_projects 
    projects.where(:owner => true) 
    end 
end 

class Project < ActiveRecord::Base 
    has_many :assignments 
    has_many :programmers, :through => :assignments 

    def owners 
    programmers.where(:owner => true) 
    end 

    def collaborators 
    programmers.where(:owner => false) 
    end 
end 

@my_programmer.own_projects 
@my_project.owners 
@my_project.owners.include? @my_programmer 
@my_project.colaborators 

UPD

另一種解決方案,使用預先加載:

class Programmer < ActiveRecord::Base 
    has_many :assignments 
    has_many :projects, :through => :assignments 
    has_many :own_projects, :class_name => "Project", :through => :assignments, :conditions => ['assignments.owner = ?', true], :source => :project 
end 

class Project < ActiveRecord::Base 
    has_many :assignments 
    has_many :programmers, :through => :assignments 
    has_many :owners, :class_name => "Programmer", :through => :assignments, :conditions => ['assignments.owner = ?', true], :source => :programmer 
    has_many :collaborators, :class_name => "Programmer", :through => :assignments, :conditions => ['assignments.owner = ?', false], :source => :programmer 
end 

@my_programmer.projects.includes(:owners).each do |project| 
    project.owner 
end 
+0

真棒,謝謝!最後一個問題。如果我想要所有不是項目所有者的人,該怎麼辦?就像@ my_project.collaborators – Ronze 2011-03-30 19:33:21

+0

看到我的更新。 – fl00r 2011-03-30 19:36:02

+0

謝謝,但這是對數據庫進行單獨調用。你將如何構建數據庫? – Ronze 2011-03-30 19:50:35