I create a new entry, for example:
truck = Truck.create(:name=>name, :user_id=>2)
My database currently has several thousand objects for the truck, but I assigned an identifier to several of them, so as to leave some identifier available. So what happens, the rails create an element with id = 150, and it works great. But then he tries to create an element and assign it id = 151, but this identifier may already exist, so I see this error:
ActiveRecord::RecordNotUnique (PG::Error: ERROR: duplicate key value violates unique constraint "companies_pkey" DETAIL: Key (id)=(151) already exists.
And the next time I run the action, it will simply assign id 152, which will work fine if this value has not yet been accepted. How can I get rails to check if an identifier exists before it is assigned?
Thank!
EDIT
Truck ID is what is duplicated. The user already exists and is a constant in this case. This is actually a problem that I have to deal with. One option is to recreate the table to allow the rails to automatically assign each identifier this time. I'm starting to think that this is the best choice, because I have a few more problems, but the migration for this will be very difficult, because Truck is the foreign key in many other tables. Will there be an easy way to have rails for creating a new table with the same data that is already stored under the truck, with automatic identification of the identifier and maintaining all existing relationships?
ruby-on-rails postgresql ruby-on-rails-3
D-Nice Jun 17 2018-12-12T00: 00Z
source share