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?
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With