2013-12-22 49 views
0

如何使用關聯訪問另一個班級。假設我有以下代碼。我怎樣才能從供應商類別獲得賬戶和賬戶歷史記錄,以及如何獲得其他兩個類別的價值。如何使用關聯訪問另一個班級

class Supplier < ActiveRecord::Base 
    has_one :account 
    has_one :account_history, through: :account 
end 

class Account < ActiveRecord::Base 
    belongs_to :supplier 
    has_one :account_history 
end 

class AccountHistory < ActiveRecord::Base 
    belongs_to :account 
end 

回答

0

你嘗試過與供應商

Supplier.find("id of that").accout 

訪問帳戶?你是否試圖訪問關於類的實例或類本身的關聯?

# How can I get account from supplier class 
Supplier.last.account 

# How can I get account history from supplier class 
Supplier.last.account.account_history 

# how can I get other two class value 
Account.last.supplier 
Account.last.account_history 
0

你想,如果你想訪問AccountHistory比

Supplier.find("id of that").accout_history 
+0

我是否能訪問account_history直接從供應商還是必須通過賬戶來訪問它像Supplier.find(「那ID」)。account.account_history – asdfkjasdfjk

+0

您可以直接訪問它。否則沒有意義定義has_one:account_history,通過::account。當你直接訪問它時會通過帳戶自動查找account_history –

相關問題