Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change primary ID of a record in Rails?

Tags:

rails console
u = User.find(9)
u.id = 7 # There is no other record with id 7
u.save
=> true
User.all

The id has not changed.

How to change the primary ID? Why does it prevent this action?

Working in Rails 3.0.7 and PostgreSQL.

EDIT: Since there are good reasons not to do this, I'll explain why and hopefully it is a good reason.

We are doing Usability Testing on Staging, so I want it to look like the Production to make it easy for everyone. I don't want to create confusion or errors in the Usability Testing process by having some things in one order on Staging and in a different order on Production. I only changed one PK id on Staging DB.

Don't do this on your production DB!

like image 201
B Seven Avatar asked Nov 28 '11 20:11

B Seven


2 Answers

I'm not sure as to why it prevents that action, but it does for sure prevent it.

You can bypass this using the update_all method on for the user.

User.where(id: 7).update_all(id: 9)

Though if possible, you really should avoid doing this.

like image 127
Kyle d'Oliveira Avatar answered Oct 15 '22 18:10

Kyle d'Oliveira


For me worked:

User.find(9).update_column(:id, 7)
like image 20
tomaszbak Avatar answered Oct 15 '22 19:10

tomaszbak