2

I want to use recently stored record ID in after_save callback, is that possible if yes how?

after_save :create_children

def create_children
 self.id
end

Update: Sorry there was something going wrong with my save function, my bad, sorry to waste your time

Thanks

2 Answers 2

5

I just tried it with this:

 class Thing < ActiveRecord::Base
   after_save :test_me

   def test_me
     puts self.id
   end
 end

and in the console:

$ rails c
Loading development environment (Rails 3.0.4)
>> x=Thing.new
=> #<Thing id: nil, name: nil, created_at: nil, updated_at: nil>
>> x.save
2
=> true
>> y=Thing.create
3
=> #<Thing id: 3, name: nil, created_at: "2011-04-27 15:57:03", updated_at: "2011-04-27 15:57:03">

What else is going on in your model?

Sign up to request clarification or add additional context in comments.

1 Comment

At least in MySql, the auto increment id column has to be set as the primary key. I had a problem where my primary key was made up of two fields -- and so ActiveRecord wouldn't read the Id. I changed it to just the ID field and the code started working.
1

if you call reload() after saving the object, the self.id will be populated

3 Comments

I tried it out, but it didnt work
I tried to use after_create as well with no luck
Sugesstion: If it is a post-processing and shouldn't affect saving of the model object, you can do it in your after_commit callback

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.