Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails select and include

Can anyone explain this?

Project.includes([:user, :company])

This executes 3 queries, one to fetch projects, one to fetch users for those projects and one to fetch companies.

Project.select("name").includes([:user, :company])

This executes 3 queries, and completely ignores the select bit.

Project.select("user.name").includes([:user, :company])

This executes 1 query with proper left joins. And still completely ignores the select.

It would seem to me that rails ignores select with includes. Ok fine, but why when I put a related model in select does it switch from issuing 3 queries to issuing 1 query?

Note that the 1 query is what I want, I just can't imagine this is the right way to get it nor why it works, but I'm not sure how else to get the results in one query (.joins seems to only use INNER JOIN which I do not in fact want, and when I manually specifcy the join conditions to .joins the search gem we're using freaks out as it tries to re-add joins with the same name).

like image 356
Chad Avatar asked Nov 12 '10 22:11

Chad


2 Answers

I had the same problem with select and includes. For eager loading of associated models I used native Rails scope 'preload' http://apidock.com/rails/ActiveRecord/QueryMethods/preload It provides eager load without skipping of 'select' at scopes chain.

I found it here https://github.com/rails/rails/pull/2303#issuecomment-3889821

Hope this tip will be helpful for someone as it was helpful for me.

like image 103
suhovius Avatar answered Sep 20 '22 06:09

suhovius


Allright so here's what I came up with...

.joins("LEFT JOIN companies companies2 ON companies2.id = projects.company_id LEFT JOIN project_types project_types2 ON project_types2.id = projects.project_type_id LEFT JOIN users users2 ON users2.id = projects.user_id") \
.select("six, fields, I, want")

Works, pain in the butt but it gets me just the data I need in one query. The only lousy part is I have to give everything a model2 alias since we're using meta_search, which seems to not be able to figure out that a table is already joined when you specify your own join conditions.

like image 35
Chad Avatar answered Sep 20 '22 06:09

Chad