Created
August 1, 2012 21:10
-
-
Save bostonaholic/3230787 to your computer and use it in GitHub Desktop.
Rails models with generated hex as parameter instead of id
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Hexable | |
def self.included(base) | |
base.class_eval do | |
before_create :generate_hex | |
attr_accessible :hex | |
end | |
end | |
def to_param | |
self.hex | |
end | |
private | |
def generate_hex | |
self.hex = SecureRandom.hex | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Post < ActiveRecord::Base | |
include Hexable | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I actually just found a great way of doing this on SO. Here's the code:
I'm sure you could use the hex in place of the base64, but your odds of running into a collision is greater and you have a lower limit of things you can store naturally.
Cheers!