Skip to content

Instantly share code, notes, and snippets.

@lypborges
Last active February 12, 2016 04:19
Show Gist options
  • Save lypborges/61f9284d62fe0ef80c15 to your computer and use it in GitHub Desktop.
Save lypborges/61f9284d62fe0ef80c15 to your computer and use it in GitHub Desktop.
Create a concern to use when using uuid as default primary key

When you use uuid some methods stop to work as expected. Using this concern in your models will do the job. All you need to do is:

1 - Copy this file to models/concerns 2 - In all your models use this concern just, like this

class Client < ActiveRecord::Base
	include Findable
end
module Findable
extend ActiveSupport::Concern
# When you use uuid some methods stop to work as expected. Using this concern in your models will do the job.
# Override methods on module FinderMethods that use id as default order when no order is defined
# It's a working in progress
# referencer:
# http://api.rubyonrails.org/classes/ActiveRecord/FinderMethods.html#method-i-take
# https://github.com/rails/rails/blob/f52354ad1d15120dcc5284714bee7ee3f052986c/activerecord/lib/active_record/relation/finder_methods.rb#L503
module ClassMethods
def first(limit = nil)
self.order("created_at").first(limit)
end
def first!
self.order("created_at").first!
end
def second
self.order("created_at").second
end
def second!
self.order("created_at").second!
end
def third
self.order("created_at").third
end
def third!
self.order("created_at").third!
end
def fourth
self.order("created_at").fourth
end
def fourth!
self.order("created_at").fourth!
end
def fifth
self.order("created_at").fifth
end
def fifth!
self.order("created_at").fifth!
end
def forty_two
self.order("created_at").forty_two
end
def forty_two!
self.order("created_at").forty_two!
end
def last(limit = nil)
self.order("created_at DESC").last(limit)
end
def last!
self.order("created_at DESC").last!
end
end
end
@tybro0103
Copy link

@lypborges
Any reason default_scope { order(:created_at) } wouldn't work?

This seems to be working well for me:

module PrimaryUuidKey
  extend ActiveSupport::Concern

  included do
    after_initialize :set_id
    self.primary_key = :id
    default_scope { order(:created_at) }
    validates :id, uniqueness: true
  end

  def set_id
    self.id ||= SecureRandom.uuid
  end

end

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