question about eager loading associations and finder_sql

I've got a situation where i have:

class Foo < ActiveRecord::Base   has_many :bars end

class Bar < ActiveRecord::Base   belongs_to :foo end

the bars table contains a column for storing cached data, which can get quite large and there are occassions when I don't want to load that data when I instantiate an object, so I thought I might do

class Foo < ActiveRecord::Base   has_many :bars   has_many :bars_without_cache, :class_name => "Bar"                   :finder_sql = 'select x, y, z from bars where foo_id = #{self.id}' end

only to find that if i eagar load the bars_without_cache association, I still get the cache data I don't want. This makes sense in a way as the whole point of eager loading is to load everything in one query so of course the finder_sql is not being used. i should have figured that.

so I guess I am asking is it possible, without having to resort to find_by_sql or having to go to n+1 queries, to eager load an association but only specific columns in the association?

Chris

Chris Hall wrote:

I've got a situation where i have:

class Foo < ActiveRecord::Base   has_many :bars end

class Bar < ActiveRecord::Base   belongs_to :foo end

the bars table contains a column for storing cached data, which can get quite large and there are occassions when I don't want to load that data when I instantiate an object, so I thought I might do

class Foo < ActiveRecord::Base   has_many :bars   has_many :bars_without_cache, :class_name => "Bar"                   :finder_sql = 'select x, y, z from bars where foo_id = #{self.id}' end

only to find that if i eagar load the bars_without_cache association, I still get the cache data I don't want. This makes sense in a way as the whole point of eager loading is to load everything in one query so of course the finder_sql is not being used. i should have figured that.

so I guess I am asking is it possible, without having to resort to find_by_sql or having to go to n+1 queries, to eager load an association but only specific columns in the association?

You'll have to use find_by_sql, and even so you'll have to install the AR mod at http://mrj.bpa.nu/eager_custom_sql.rb so you can eager load the bars.

You can prevent having to repeat yourself by defining a method like:

class Foo < ActiveRecord::Base

   def find_including_bars_without_cache(options = {})      sql = '...'      sql << "where #{options[:conditions]}" unless options[:conditions].nil?      find_by_sql( sql, :include => :bars )    end

end

thanks for the info. I'll look into that.

Chris