Rails 3 how to get the current record ID in after_create

7.1k views Asked by At

Like the title said, I'm trying to get the ID of the record I just created, I tried to get it in the console but the ID is nil.

Here is the print I got of self in the console at the beginning of after_create

<Unit id: nil, uuid: "9f11be13-8d07-4471-a3bb-f87943966bbd", organization_id: 33, property_id: 430, door_number: "3", created_at: "2014-12-05 13:27:57", updated_at: "2014-12-05 13:27:57", deleted_at: nil, size: "5 1/2", door_number_int: 3, leases_count: 0, tasks_count: 0, notes: nil, state_id: 68, state_tasks_count: 2, current_lease_id: nil, next_lease_id: nil, state_tasks_serie: 1, state_tasks_serie_count: 2, price_asked: #<BigDecimal:7fc79162cb80,'0.123E3',9(18)>, availability_date: nil, comments_count: 0>

Is there a way to get access to the record ID?

This is what I tried so far

after_create
   self.save
end

before_save
  if self.id.present?
    # do stuff
  end
end

It is not very pretty but it work

To answer @MarekLipka : It doesn't cause an infinite loop because the record is created only once.

I also tried to use :

after_create
   reload

   # do stuff if self.id
end

but that doesn't seem to work.

Like @PauloFidalgo said, I can't get the id except in the after_save method. Although it is strange to me that I can get it in the second before_save (triggered by the save in after_create).

1

There are 1 answers

4
Paulo Fidalgo On BEST ANSWER

The id is only assigned on save, on create you are just creating the skeleton object and giving some values.

To get the id of the object just call object.id

If for some reason you want to get the id in the after_* methods, you need to use the after_save:

 after_save {id = self.id}

You could also allocate an ID in create, but you need to query the database and set the value in the variable. To achieve this you need to use a sequence in database to set the id's.