trevorhinesley
trevorhinesley

Reputation: 875

How do I get the next available unique ID in Rails without calling Model.last.id?

I populated a database, then deleted all the users. Now I need to get the next available ID (the last one used was 109, but I need this to work in any situation where this happens, not just my unique one) without calling Model.all.last. Is this possible, and how do I do it?

Upvotes: 0

Views: 1500

Answers (2)

mu is too short
mu is too short

Reputation: 434665

When you create the table for an ActiveRecord Model class, you'll get a table called models. The ids for this table will be a serial column which gets its values from the models_id_seq sequence. You can get the last value that this sequence generated with this:

select last_value from models_id_seq

so all you need is a simple select_value call:

last_id = ActiveRecord::Base.connection
                            .select_value('select last_value from models_id_seq')
                            .to_i

Keep in mind that you will run into trouble is something else is working with your table while you're trying to find the last id value. This is also PostgreSQL-specific but you've tagged this with so that shouldn't be a problem.

Upvotes: 4

Tomanow
Tomanow

Reputation: 7367

To do it dynamically I'd say your best bet is to store the value in another table. You could do this with a trigger that updates the field each time a record is added. This method does not rely on your rails app so it is probably a better way than doing it in ruby.

Also, If you just need it occasionally for manual updates, I know if you are using something like phpmyadmin you can get the value by looking in the table structure at the bottom it will say "Next autoindex".

Upvotes: 0

Related Questions