views:

21

answers:

0

I have two models, with a habtm relationship. When I create new instance and call include? on the association, rails hits the database each time. That doesn't seem very good for performance.

Eg.:

class Foo < ActiveRecord::Base
  has_and_belongs_to_many :bars
  default_scope :include => [:bars]
end

class Bar < ActiveRecord::Base
  has_and_belongs_to_many :foos
  default_scope :include => [:foos]
end

Loading development environment (Rails 2.3.5)
>> Bar.new.foos.include? Foo.new
=> false

Foo Load (0.2ms)   SELECT "foos".id FROM "foos" INNER JOIN "bars_foos" ON "foos".id = "bars_foos".foo_id WHERE ("foos"."id" = NULL) AND ("bars_foos".bar_id = NULL ) LIMIT 1

I have found that I can suppress this behavior by assigning an empty array to the associations upon initialization. Eg. if I add the following code:

class Bar < ActiveRecord::Base
  has_and_belongs_to_many :foos
  default_scope :include => [:foos]
  def after_initialize
    self.foos = []
  end
end

Am I doing something really backwards here?