Baozi Wu
Baozi Wu

Reputation: 53

Can rails get the next id after destroying a record?

Suppose that I have two records in database:

Dogs table:
id:1, name:Paotzu
id:3, name:Baozi

now I am going to destroy the id 3 (Dog.find(3).destroy)
and then the table is being that:

Dogs table:
id:1, name:Paotzu

OK, now I have a question,
If I don't create a new record, how can I get the Next ID in rails console ?
Somebody told me Dog.last.id + 1, but it is incorrect.
Because if I type Dog.last.id + 1, I will get 2, but I want get 4 (that's I've created.)

Upvotes: 0

Views: 290

Answers (4)

Stefan
Stefan

Reputation: 114168

You could use a custom SQL query (this one is for MySQL):

sql = "SHOW TABLE STATUS LIKE 'Dogs'"
result = ActiveRecord::Base.connection.execute(sql)
result.each(as: :hash).first['Auto_increment']
#=> 4

Upvotes: 0

Nithin
Nithin

Reputation: 3699

@dog_rec = Dog.find(3).destroy 
@next_rec = Dog.find(:first, :conditions => ["id > ?", @dog_rec.id])

rails can do anything ;)

Upvotes: 2

RoyTheBoy
RoyTheBoy

Reputation: 658

This would do it

Dog.where("created_at > ?", 30.days.ago).order("created_at DESC").first.id

Upvotes: 0

Bharat soni
Bharat soni

Reputation: 2786

Hey buddy new record will get id automatically, why you are required such thinks to do.

Upvotes: 1

Related Questions