Building associations

I have a model with has_many (not :through) and am adding members to it like this:

class Panda < AR::Base   has_many :baby_bears, :after_add => :increment_baby_count

  def do_it    self.baby_bears << BabyBear.create({:name => "Fluffy"})   end end

In looking at the log, this results in 2 SQL statements, an INSERT (for the create) immediately followed by an UPDATE of the same record (no changes were made!).

If I look in vendor/rails/active_record/lib/active_record/associations/ has_many_associations.rb#insert_record

which handles the over-loading of the "<<" method I can see that it is blindly calling "record.save", which is the cause of the UPDATE. In this case its the perfect situation for ActiveRecord supporting a "dirty" bit.

However, I think that I am not doing this correctly. That is, I am not adding my association member correctly.

If I use "self.baby_bears.create({:name => "Fluffy"})" then my :after_add callback does NOT get called, but it does get called in the first method.

In summary:

How do I add an association member that does not generate 2 SQL statements AND get my :after_add callback executed?

Thanks in advance.

Wiliam Langshaw wrote:

How do I add an association member that does not generate 2 SQL statements AND get my :after_add callback executed?

What about

    self.baby_bears << BabyBear.new(:name => "Fluffy")

or simply

self.baby_bears.create(:name => "Fluffy")

Yup, thats the ticket, using "new" versus "create". I should have thought of that before, I feel like an idiot!

@Thorsten: your idea of

self.baby_bears.create(:name => "Fluffy")

does *not* (completely) work because the :after_add callback is not being triggered.

Thanks!