2017-07-24 71 views
0

獲得相關資源的頭銜,我有2種型號的連接是這樣的(客戶和項目):的Rails通過ID

class Project < ActiveRecord::Base 
    belongs_to :cliente 
end 

class Cliente < ActiveRecord::Base 
    has_many :projects 
end 

項目在其架構中的一個:cliente_id列,所以,如果我做的:

Project.cliente_id我會正確得到cliente_id。

我的疑問是,我想要得到客戶端名稱從它的ID,所以我需要的東西,如:

Project.cliente_id.name 

這是獲取這些信息的正確方法是什麼?

回答

2

您可以使用project.cliente(請注意不使用_id)獲得完整的Cliente對象。所以你可以像普通的Cliente一樣使用它;例如,獲得name只是做:

project = Project.find(1) 
project.cliente.name 
+0

我會得到:未定義的方法'名」的零:NilClass,在此先感謝 – Gibson

+0

好,謝謝!我不得不檢查一下客戶是否先關聯。作爲魅力工作! – Gibson

+0

這個答案將該類與實例混淆。例如,'Project.cliente'試圖調用一個類對象的實例方法。這個答案是錯誤的,它在語法上不正確。 – anothermh

2

您找到相關對象through the association

project = Project.find(1) # Returns the full `project` object 
project.cliente # Returns the full `cliente` object 
project.cliente.name # Returns just the `name` attribute 
project.cliente_id == project.cliente.id # Returns true