轨道:使用选择连接



我有两个模型:- 客户和帐户。
客户has_one帐户和客户belongs_to帐户 我想连接表并仅获取一些字段。我的代码:-

Customer.joins(:account).select("customers.id, customers.name, accounts.opening_balance")

它给了我客户::ActiveRecord_Relation的结果是这样的:-

[#<Customer:0x00000005be0870 id: 1774, name: "James TEA">,
#<Customer:0x00000005be0730 id: 1777, name: "Joseph STORE">,
#<Customer:0x00000005be0578 id: 1835, name: "John CONFECTIONARY">,
#<Customer:0x00000005be03e8 id: 1836, name: "Jerry PAN SHOP">]

无论我做什么,我都无法从正确的表中获取字段(在本例中为帐户(。有什么帮助吗?

尝试:

customers = Customer.joins(:account).select("customers.id, customers.name, accounts.opening_balance as opening_balance")
customers.first.opening_balance

最新更新