2014-06-27 71 views
0

目前,我在軌道上4.1,如何在rails 4.1中檢索自動遞增的ID?

我有一個名爲accounts.rb模型,

account = Account.create :name => 'test' :info => 'test' 

所以這種說法是保存到數據庫,然後 我使用「account.id」的自動增量ID在帳戶表中。

但不工作,並顯示以下錯誤,

undefined method `id' for "":String 

但這是在軌工作1.9版本。

請幫幫我。

+1

你是不是缺少一個逗號呢? –

+0

只需在記錄創建後使用'account.id' – Nithin

+0

我沒有看到任何問題,對我來說工作得很好。你可以發佈'accounts.rb'嗎? –

回答

1

對象

你的方法似乎是正確的;你的語法似乎有一個問題

undefined method `id' for "":String 

這基本上意味着你調用一個對象,它只是一個字符串,在那個空單在id方法。

因此,我認爲這個問題是不是與你的auto increment號做的,它與你如何調用新對象的id

做 -

創建

標準要做到這一點的方法將使用以下內容:

#controller 
account = Account.create({name: "test", info: "test"}) 
return account.id 

根據create文檔,此應爲爲你工作。如果沒有,你不妨使用.new.save方法,像這樣:

#controller 
account = Account.new({name: "test", info: "test"}) 
if account.save 
    return account.id 
end