简体   繁体   中英

Rails: joins with select

I have two models:- Customer and Account.
Customer has_one account and account belongs_to customer I want to join the tables and fetch only some fields. My code:-

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

It gives me Customer::ActiveRecord_Relation in result like this:-

 [#<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">]

No matter what I do, I am not able to get fields from right table(account in this case). Any help?

Try:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM