Last active
January 3, 2021 20:55
-
-
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`
This file contains hidden or 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
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For this to work, the model needs an attribute
uuid
(string), which should be indexed. Once that is in place you can:Also in controllers and route path methods, find or specify uuid rather than id. So