Skip to content

Instantly share code, notes, and snippets.

@herenow
Last active June 4, 2017 04:19
Show Gist options
  • Save herenow/07a93ed1bd2173668457e2e169df93c0 to your computer and use it in GitHub Desktop.
Save herenow/07a93ed1bd2173668457e2e169df93c0 to your computer and use it in GitHub Desktop.
Default Rails primary_key and references to string (monkey patch)
# By default, rails expects id's to be a integer
# In our app, we store id's as strings.
#
# To make our life easier, instead of always having to remember this
# and explicitly telling rails the id is a string, I'm going to monkey
# patch some migrations and AR methods.
module CoreExtensions
module ActiveRecord
module ConnectionAdapters
module ReferenceDefinition
def initialize(name, options = {})
options.reverse_merge!(
type: :string,
)
super
end
end
module TableDefinition
def primary_key(name, type = :string, **options)
# Only overide primary_key when options[:nil] is not set
# It will be set, when a custom primary_key type is passed
# for create_table, e.g:
#
# create_table :table, id: :custom_type do ...
#
# see:
# https://github.com/rails/rails/blob/d357da68ff06d10bc074f84eb09b4d9144c4136f/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb#L299
if options[:id].nil? && type == :primary_key
type = :string
end
super
end
end
end
end
end
# Add monkey patches
ActiveRecord::ConnectionAdapters::ReferenceDefinition.prepend(
CoreExtensions::ActiveRecord::ConnectionAdapters::ReferenceDefinition
)
ActiveRecord::ConnectionAdapters::TableDefinition.prepend(
CoreExtensions::ActiveRecord::ConnectionAdapters::TableDefinition
)
@herenow
Copy link
Author

herenow commented Jun 4, 2017

Change types from :string to :uuid to default to auto generated uuid primary keys, when on postgresql adapter.

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