Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails eager load association with selected attributes

Can anyone tell me if it's possible to eager load an association but only return specific attributes?

I'd like to retrieve some orders with their accounts but only require the account names.

Order.select([:id, :account_id]).includes(:account).limit(2)

like image 640
Chris Hilton Avatar asked Mar 12 '13 09:03

Chris Hilton


1 Answers

I think jvnill's comment says it all:

I'm not sure that is possible. You can however add the account_name to the returned order records.

orders = Order.joins(:account).select('orders.id, orders.account_id, accounts.name AS account_name')

then just use account_name like orders.first.account_name

like image 137
Chris Hilton Avatar answered Sep 20 '22 19:09

Chris Hilton