如何使用关联访问另一个类

时间:2013-12-22 05:54:20

标签: ruby-on-rails

如何使用关联从另一个类访问一个类。说我有以下代码。如何从供应商类获取帐户和帐户历史记录,并形成帐户类,如何获得其他两个类值。

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

2 个答案:

答案 0 :(得分:0)

您想要访问供应商帐户

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

如果您想访问AccountHistory而不是

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

答案 1 :(得分:0)

你有什么尝试?您是在尝试访问类实例或类本身的关联吗?

# 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