2016-03-10 31 views
0

當一個對象保存在rails中時,它的DB中的ID被分配給它。但它實際上並未保存在數據庫中。 在控制檯上,我沒有看到除INSERT查詢以外的任何查詢,這是在after_save之後執行的。Rails如何爲after_save中的對象分配id

那麼,在INSERT查詢之前,rails如何將id分配給對象。

回答

0

對於不同的dbs有不同的方法。有關更多詳細信息,您必須查看AR模型或您正在使用的任何其他ORM。

爲PG看看 - rails postgres insert

如果你沒有得到你記錄的ID,顯示從schema.rb

0

通常更多的細節,這是由數據庫本身完成。通常,表的id列是auto_increment column,這意味着數據庫將保留自動遞增計數器並在保存時將其值分配給新記錄。然後,Rails必須在插入記錄後將新分配的id從數據庫中取出。

這是插入新行時,DB(see docs for the insert method)的Rails做什麼:

# 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 

因此,在實踐中,ID不會從Rails的傳入的INSERT語句。但是在插入之後,創建的Rails對象將定義它的id

+0

我明白了,順便說一句[這個SO答案](http://stackoverflow.com/a/5807026/1544012)包括一個測試,在'after_save'回調中訪問'id'。 – BoraMa

+0

我想知道這究竟發生了什麼? 我的意思是當查詢沒有執行時,這個'id'來自哪裏。 –