views:

350

answers:

2

OK, I've been playing around with some of the eager loading things, and have 2 models something like:

Class Recipe < ActiveRecord::Base
    belongs_to :cookbook
    has_many   :recipetags
end

and

Class Cookbook < ActiveRecord::Base
    has_many :recipes, :include => [:recipetags]
end

Which is working out well, when I find a Cookbook, then I eager load the recipes, and in turn the recipes eager load the :recipetags:

cb = Cookbook.find(10590, :include => [:recipes])

But what I want to also do is whenever I open a recipe, have it pull in all of it's eager associations automatically - basically I want to do:

rec = Recipe.find(123)

and have it eager load the :recipetags in that case as well.

I realize this seems trivial, but in actuality I have about 4-5 associations on Recipe, I'm just not showing them here, and rather than having to explicitly do the :include on every find call I'd like it to just happen. I'm assuming I can override Recipe.find to do it in the Recipe model, but was wondering if there was a cleaner way....

A: 

You should be able to do this with named scopes, but I understand that there were a number of possible bugs with that, hopefully they are all fixed now.

fd
+5  A: 

I've been using default_scope to do it on selected models where I always want to eager load:

class Post < ActiveRecord::Base
  has_many :comments
  default_scope :include => :comments, :order => ["title ASC"]
  ...
end
Dan McNevin
This looks good - although it looks like it's only available in 2.3+, which introduced some other problems in the app. I'll see if I can get 2.3.2 working and test it out.
Cameron Ferroni