I want to use auto-generated hash'es instead of auto-incremented integers in my activerecords as primary keys. This raises two questions:
Regards, Mateusz
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.
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).
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With