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.

2 Answers 2

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

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

Comments

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.

2 Comments

I see, BTW this SO answer includes a test with accessing id in an after_save callback.
I wanted to know exactly how does this happen? I mean where does this id come from when the query has not been executed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.