In Ruby on Rails, how do I create an entry with ID 3 when it was destroyed before?

I'm trying an experimental Rails project and destroyed record 3 (ID == 3), so now there is record 1, 2, 4 and 5.

Is there a way to overwrite this table with a record ID from 1 to 5? (this uses mysql)

I can use

if Item.exists?(i)
  item = Item.find(i)
else
  item = Item.new
end

# set some values
item.name = "haha" + i
item.save

Item.new() is to create new records with new auto-increment record identifiers (in this case 6), but what about those that were previously deleted?

+3
source share
3 answers

You can set the identifier using:

item = Item.new
item.id = i

:id => i Item.new, id .

MySQL, 1 , :

Item.connection.execute("ALTER TABLE items AUTO_INCREMENT = 1")

( , MySQL docs , reset MAX(id) + 1, 3).

+8

MySQL , , , . , , . ( , id , .) , :

  • , .
  • . , URL-, , - , . .

, , . , №3, ... - .

+2

You can do it as @wuputah said. And furthermore, we usually should not delete records from the table, if otherwise it is not the main table (since this may affect the relations of other tables). Instead, we can have inactive records (for example, have a table column called active)

And make things simpler, you can use a plugin like act_as_paranoid to achieve this http://github.com/technoweenie/acts_as_paranoid

amuses

Sameera

+1
source

Source: https://habr.com/ru/post/1761549/


All Articles