How to change primary ID of a record in Rails?

后端 未结 6 1827
野的像风
野的像风 2020-12-28 16:10
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

6条回答
  •  太阳男子
    2020-12-28 16:42

    Another method (although it is not pure Rails) is to create a new column, and populate it with your new IDs.

    Then, using DB management software (not Rails), remove the Primary Key attribute from the id column, delete it, rename your recently added column to "id", and give it the Primary Key attributes. (If you cannot do that directly in your DB software, then set the properties Unique, Auto-Increment, etc.)

    You can also move the column to the front (MySQL syntax):

    ALTER TABLE table_name MODIFY COLUMN id int(11) FIRST;
    

    But there is another thing I'd really like to say. It hasn't been as bad on this question as I've seen elsewhere, but folks: it's all well and good to tell people it's USUALLY not a good idea, but that isn't an answer to the question. Please refrain from saying "Don't do that" unless you already know the person's use-case.

    In other forums I've been greatly frustrated by people saying "Why do you want to do that?" or "Don't do that", and then not answering the question. They didn't give me credit for already KNOWING that it isn't standard practice, and they ASSUMED I didn't already know that it was not an ordinary use-case.

    People on this page haven't been that bad, and I'm not trying to pick on them. I'm just admonishing: please, check your own behavior before presuming to lecture. Somebody asked a question, and while warnings may be a good idea, it is probably safe to presume they have a REASON for wanting an answer.

    End of rant.

提交回复
热议问题