Search code examples
ruby-on-railspostgresqlpglibpq

In a PostgreSQL/Rails app, what decides how the 'id' field is allocated when 'create' method is called?


I have a model called "Post". Because of reasons, I had to create Posts with specific id values. When I run Post.last, it gives me the Post with the highest id value. However, when I run Post.create(), it tries to create a Post with an id greater by 1 than the id of the last Post created without a specified id.

The number of Posts in my database created without a specified id has now caught up to the id of the first Post whose id I specified. This results in an error, because the Post that Rails tries to create would have an id value that's already taken.

Is it possible to somehow override id allocation, to make it go by the value of Post.last.id?


Solution

  • The IDs are generated by a Postgres sequence. Rails will have generated this for you as part of a rails generate model Post, and if you went with all the defaults, your table is called posts and the sequence should be called posts_id_seq.

    You need to reset the sequence to the next value after the ID you've already used.

    If the next value you want to use is, for example, 5000, something like

    ALTER SEQUENCE posts_id_seq RESTART WITH 5000;