2013-12-22 20 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 –

相关问题