Rails : Mass assignment with ids in seeds.rb | PG::UniqueViolation: ERROR

Looks like you can mass-assign records into ActiveRecord models without any problem like

                    { parent_id: 1, name: 'Computer Science', description: 'Readable via Electronic devices.' },
                    { parent_id: 1, name: 'Electronics' },
                    { parent_id: 1, name: 'Law' },
                    { parent_id: 1, name: 'Social' }

But you cannot do like

                    { id: 1, name: 'Ebooks', description: 'All the books readable via Electronic devices.' },
                    { id: 2, name: 'Slides' },
                    { id: 3, name: 'Documents' },
                    { id: 4, name: 'Web Templates and Themes' },
                    { id: 5, name: 'License' }

if you did, it will create records but after that if you try to create even a new record, you wont be able to; you will this error

PG::UniqueViolation: ERROR: duplicate key value violates unique constraint "categories_pkey"
DETAIL: Key (id)=(1) already exists.


could not find any proper explanation. If you find, please comment here below. However my theory is:

When ever you create a record with explicitly supplying primary_key (:id field) rails does not keep track of fact that the record with id==1 has already been created and tries to create the record again with prexisting ID and Database throws an Exception.

useful links



Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s