after_save question

Hi all,

In my model class I need to update an attribute with the ID of the record right after the model object has been saved.
I intended to use the after_save callback for this purpose.

I don’t know how to update this automatically after saving an
object. Calling save in the after_save hook, causes an infinite loop.
Write_attribute does not save to the Database. What can I do, to make
this happen auto-magically?

class Product < ActiveRecord::Base

after_save :update_lineage

def update_lineage
write_attribute(:lineage, “#{id},”) # this does not save the attribute to the db
# save! # this does save, but calls the after_save callback again, causing a infinite loop

end

end

Thanks,

Harm de Laat

Hi Harm,

class Product < ActiveRecord::Base

-after_save :update_lineage
+after_create :update_lineage

  def update_lineage

- write_attribute(:lineage, "#{id},") # this does not save the
- attribute to the db
- # save! # this does save, but calls the after_save callback again,
- causing a infinite loop
+ update_attribute :lineage, "#{id},"

  end

end

Regards
Florian