Pisto
Pisto

Reputation: 181

Can we use the ids again for whom the record has been deleted?

I was doing RoR tutorial wherein we could add,update,delete user details in the application and simultaneously an id gets auto defined with user,but once we delete a user details then for that id it displays record not found. Can we use that id again?

Upvotes: 1

Views: 1340

Answers (3)

Ariejan
Ariejan

Reputation: 11069

I do not recommend re-using unique ID's.

First, ask yourself why do you assign unique ID's to users:

  • To uniquely identify users
  • To create unique URLs to a user's resources
  • To link other objects (orders, blog posts, game data) to that specific user

So, if you've deleted a user - what happens?

In almost every app I've written a user always leaves traces. Either from URLs that were once exposed to the internet (think indexed by google) or data from that user that's kept as records (orders, etc).

Reusing a user ID would cause problems - and thus work to refactor the application to cope with those problems. In 99% of these cases the easiest solution it to just keep generating new, unique IDs for those users.

There are also situations that you need to keep data from a deleted user around (e.g. financial systems and webshop are good examples). This would keep the unique ID alive after the user is deleted - you can't reuse it.

TL;DR: Reusing unique IDs is possible, but poses problems. Easiest solution around those problems is generating new unique IDs.

As an added note, unique IDs don't have to be auto incremented integers.

Upvotes: 0

Peter Nixey
Peter Nixey

Reputation: 16565

From your comments it looks like you're trying to save on using high-value IDs by re-using lower value IDs after they've been freed. In general this is not considered a good idea.

The likelihood that you will run out of IDs at the top end is minimal (zero if you keep making your ID column accept larger integers) however reassigning IDs has the potential to open you up to problems. If, for instance you wanted to delete a user but keep content they had created (e.g. blog posts) then reassigning the IDs would mean that the new ID owner becomes the owner of those old comments.

It feels wasteful but the best thing to do is just leave old, vacant IDs vacant and eat up new ones.

Upvotes: 8

fl00r
fl00r

Reputation: 83680

You can use something like this (Rails 3 syntax)

@user = User.find_by_id(params[:id]) || User.where("id > ", params[:id]).first || User.where("id < ", params[:id]).last

Upvotes: 0

Related Questions