Skip to content

Instantly share code, notes, and snippets.

@reggieb
Last active January 3, 2021 20:55
Show Gist options
  • Save reggieb/db5f55b4f4dad23322db1c07ba60029e to your computer and use it in GitHub Desktop.
Save reggieb/db5f55b4f4dad23322db1c07ba60029e to your computer and use it in GitHub Desktop.
UUID concern for rails models - To allow rails paths to be of the form `foo/63950bdb-6c3b-4744-ad6f-f5df5aed1a76` rather than `foo/1`
require 'active_support/concern'
module UseUuid
extend ActiveSupport::Concern
included do
before_save :generate_uuid
end
def to_param
uuid
end
private
def generate_uuid
return true if uuid?
self.uuid = SecureRandom.uuid
end
end
@reggieb
Copy link
Author

reggieb commented Aug 31, 2016

For this to work, the model needs an attribute uuid (string), which should be indexed. Once that is in place you can:

class Foo < ActiveRecord::Base
  include UseUuid
end

Also in controllers and route path methods, find or specify uuid rather than id. So

# Without uuid
foo = Foo.find(params[:id])
redirect_to foo_path(foo)

# With uuid
foo = Foo.find_by(uuid: params[:id])
redirect_to foo_path(id: foo.uuid)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment