Yella Goud
Yella Goud

Reputation: 157

How to retrieve auto incremented id in rails 4.1?

Currently i am working on rails 4.1,

I have a model called accounts.rb,

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

So this statement is saving to database, Then i am using "account.id" which auto increment id in accounts table.

But that is not working and showing following error,

undefined method `id' for "":String  

But this was worked in rails 1.9 version .

Please help me.

Upvotes: 0

Views: 134

Answers (1)

Richard Peck
Richard Peck

Reputation: 76774

Object

Your method seems correct; your syntax seems to have an issue

undefined method `id' for "":String

This basically means you're calling the id method on an object which is just a string, an empty one at that.

I would therefore say the problem is not to do with your auto increment number, it's to do with how you're calling the id of the new object

--

Create

The standard way to do this would be to use the following:

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

According to the create documentation, this should work for you. If it doesn't, you may wish to use the .new with .save methods, like this:

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

Upvotes: 1

Related Questions