selectable_includes

Created: 2008-12-20 21:47
Updated: 2014-02-20 15:53

README.markdown

Selectable Includes

Active Record has two strategies for :include. In one each association is loaded with a query and in the other a single query with lots of tasty joins loads all of the associations. In this latter form Active Record ignores any :select option you pass because it needs to control how all the retrieved columns are aliased in order to put all the records together.

This plugin allows the :select option to be taken into account in such circumstances. Unlike a normal :select option it does not replace the select statement generated by Active Record (since would break the eager loading) but is prepended to it. What this means is that you cannot control which columns are selected, but you can piggy back attributes.

For example

Post.find :all, :include => :comments, :order => 'comments.created_at desc', :select => "posts.title"

accomplishes nothing

whereas

Post.find :all, :include => :comments, :order => 'comments.created_at desc', :select => "(SELECT COUNT(*) from favourite_posts where posts.id = favourite_posts.post_id) as favourite_count"

would piggy back the number of times the post was added to someone's favourite to the list of fetched posts.

You could also use this if you wanted a query that looked like

SELECT SQL_NO_CACHE ...

you could do

Post.find :all, :include => :comments, :order => 'comments.created_at desc', :select => "SQL_NO_CACHE"

This plugin has no effect in cases where the joins base include code is not used.

Cookies help us deliver our services. By using our services, you agree to our use of cookies Learn more