Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

hash instead of id

I want to use auto-generated hash'es instead of auto-incremented integers in my activerecords as primary keys. This raises two questions:

  1. how to perform this generation in most efficient way?
  2. how to handle possibility that generated hash exists already in table?

Regards, Mateusz

like image 473
Mateusz Avatar asked Mar 31 '11 08:03

Mateusz


People also ask

Is hash the same as ID?

NO! A hash code is not an id, and it doesn't return a unique value. This is kind of obvious, when you think about it: GetHashCode returns an Int32 , which has “only” about 4.2 billion possible values, and there's potentially an infinity of different objects, so some of them are bound to have the same hash code.

Can I use hash key as a unique ID?

No, you don't want to use a hash as the ID, especially if you are making the ID the Primary Key and will have tables Foreign Keyed to this table. An SHA1 hash is 20 bytes and cannot be decoded (i.e. you cannot derive the source values from it).

What is the difference between id and hash in Python?

Unequal objects may have the same hash values. Equal objects need to have the same id values. Whenever obj1 is obj2 is called, the id values of both objects is compared, not their hash values.

What is a hashID?

hashID is a tool written in Python 3. x which supports the identification of over 175 unique hash types using regular expressions. It is able to identify a single hash or parse a file and identify the hashes within it.


1 Answers

If you want this because you don't want to show the id in the web url. You can use a gem like https://github.com/peterhellberg/hashids.rb

It creates a reversible hash from your database id so the hash does not need to be stored in the database.

Use it in your models to_param method.

class MyModel < ActiveRecord::Base

  def to_param
    Hashids.new("salt").encode(id)
  end
end

And decode the hash before finding the record from the database.

def show
  id = Hashids.new("salt").decode(params[:id]).try(:first)
  record = MyModel.find(id)
end
like image 134
Mika Avatar answered Sep 21 '22 21:09

Mika