IncludeByDefault
Installation
script/plugin install git://github.com/jcoglan/include_by_default
This plugin allows you to specify which associations should be eager-loaded automatically when you do a find on one of your models. Read about eager loading in the Rails docs: api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html
This saves you having to write :include all over the place to minimise your database queries. Instead, you can put whatever you‘d usually specify using :include in one declaration in your model. Say you have a photoblog that allows comments. Then your entry model might look like this:
class BlogEntry << ActiveRecord::Base
has_many :photos
has_many :comments
include_by_default :photos, :comments
end
The associations will now be loaded automatically along with any BlogEntry record you find. If you specify :include explicitly in any find operation, that will override the default specified in the model.
Bugs
As well as the functionality stated above, IncludeByDefault attempts to fix a couple of bugs in ActiveRecord:
The first is a problem with cascaded many-to-many queries. e.g.
Tag.find(8).entries.find(:all, :include => :tags)
will usually raise an exception. IncludeByDefault fixes this by overloading ActiveRecord::Base.add_joins! so that it re-aliases any duplicate table names to disambiguate the SQL generated.
The second is a problem that stops you using the :joins option on scoped many-to-many find operations. That is, you cannot do
Tag.find(8).entries.find(:all, :joins => sql_fragment)
if Tag and Entry are many-to-many. My rewrite of ActiveRecord::Base.add_joins! allows you do this. The rewrite does the table aliasing on the existing SQL before appending the new JOIN fragment, so the table names you use for :joins should be retained.
License
Copyright (c) 2007 James Coglan
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.