Umesh Malhotra
Umesh Malhotra

Reputation: 1047

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?

Upvotes: 1

Views: 2161

Answers (1)

apneadiving
apneadiving

Reputation: 115521

Try:

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

Upvotes: 2

Related Questions