8

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)

Chris Hilton
  • 717
  • 1
  • 8
  • 13
  • 4
    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` – jvnill Mar 12 '13 at 10:51
  • That's what I thought from my google research so thanks for the confirmation – Chris Hilton Mar 12 '13 at 16:11

1 Answers1

5

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

Peter Brown
  • 50,956
  • 18
  • 113
  • 146
Chris Hilton
  • 717
  • 1
  • 8
  • 13
  • 4
    I am also curious about this. Isn't there any way to eager load only specific columns or any find_by_sql tricks. – roxxypoxxy Sep 24 '13 at 18:01