Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3 - select with Include?

Here is a nested select with include:

@items = Item.where("complete = ?", true).includes( :manufacturer, {:order=>[:supplier, :agent] }) 

This is a taxing query as it pulls 1000s of rows of data from all the above included tables.

How can I get the query to only select specific fields?

  • user.name, user.created_at
  • order.created_at
  • supplier.name
  • agent.name
  • manufacturer.name
like image 336
sscirrus Avatar asked Oct 28 '10 23:10

sscirrus


1 Answers

There is a select method in ARel, but you must use the correct table names (i.e. plural and beware if you have polymorphic models or if you're using set_table_name or some other similar non-standard practice)

@items = Item.   select('users.name', 'users.created_at', 'orders.created_at', 'suppliers.name', 'agents.name', 'manufacturers.name').   where(:users => { :fulfilled => true }).   includes(:orders => [:supplier, :agent], :manufacturer) 

"We can use select with joins not includes" - @Bhavesh_A_P

Note:

As @Bhavesh_A_P pointed out above, select with includes does not produce consistent behavior. It appears that if the included association returns no results, select will work properly, if it returns results, the select statement will have no effect. In fact, it will be completely ignored, such that your select statement could reference invalid table names and no error would be produced. select with joins will produce consistent behavior.

like image 57
Patrick Klingemann Avatar answered Sep 22 '22 01:09

Patrick Klingemann