0

When an object is saved in rails, it's ID in DB is assigned to it. But it is not actually saved in the DB. On the console, I haven't seen any query being fired other than the INSERT query, which is performed after the after_save.

So how does rails assign the id to the object before the INSERT query.

Abhishek Kumar
  • 674
  • 1
  • 6
  • 15

2 Answers2

0

There are different ways for different dbs. For more details you have to look through the AR models or any other ORM you are using.

For pg see - rails postgres insert

If you don't get an ID in you records, show more details from schema.rb

Community
  • 1
  • 1
devanand
  • 5,116
  • 2
  • 20
  • 19
0

Typically, this is done by the database itself. Usually, the id column of a table is an auto_increment column which means that the database will keep an auto incrementing counter and assign its value to the new record when saved. Then, Rails has to pull the newly assigned id back from the database after inserting the record.

This is what Rails does when inserting a new row to DB (see docs for the insert method):

# ActiveRecord::ConnectionAdapters::DatabaseStatements#insert
#
# Returns the last auto-generated ID from the affected table.
#
# +id_value+ will be returned unless the value is nil, in
# which case the database will attempt to calculate the last inserted
# id and return that value.
#
# If the next id was calculated in advance (as in Oracle), it should be
# passed in as +id_value+.
def insert(arel, name = nil, pk = nil, id_value = nil, sequence_name = nil, binds = [])
  sql, binds = sql_for_insert(to_sql(arel, binds), pk, id_value, sequence_name, binds)
  value      = exec_insert(sql, name, binds, pk, sequence_name)
  id_value || last_inserted_id(value)
end

So, in practice, the ID is never passed from Rails in the INSERT statement. But after the insert, the created Rails object will have it's id defined.

Matouš Borák
  • 15,606
  • 1
  • 42
  • 53
  • I see, BTW [this SO answer](http://stackoverflow.com/a/5807026/1544012) includes a test with accessing `id` in an `after_save` callback. – Matouš Borák Mar 10 '16 at 21:51
  • I wanted to know exactly how does this happen? I mean where does this `id` come from when the query has not been executed. – Abhishek Kumar Apr 03 '16 at 16:44