Override the Rails create_table migration template

Override the Rails create_table migration template
Do not index
Do not index
In the previous post about using a ULID as a primary key for you ActiveRecord models I described the changes needed for the create_table migrations. I like to not think about that all the time and run into weird errors while migration my database when I forgot to make the id a binary type.
For this we can override the create_table_migration template that Rails uses. Just add a file at this location lib/template/migration/templates/create_table_migration.rb.ttin your Rails application and add the following:
class <%= migration_class_name %> < ActiveRecord::Migration[<%= ActiveRecord::Migration.current_version %>]
  def change
    create_table :<%= table_name %>, id: false do |t|
      t.binary :id, limit: 16, primary_key: true
<% attributes.each do |attribute| -%>
<% if attribute.password_digest? -%>
      t.string :password_digest<%= attribute.inject_options %>
<% elsif attribute.token? -%>
      t.string :<%= attribute.name %><%= attribute.inject_options %>
<% elsif attribute.reference? -%>
      t.<%= attribute.type %> :<%= attribute.name %><%= attribute.inject_options %><%= foreign_key_type %>
<% elsif !attribute.virtual? -%>
      t.<%= attribute.type %> :<%= attribute.name %><%= attribute.inject_options %>
<% end -%>
<% end -%>
<% if options[:timestamps] %>
<% end -%>
<% attributes.select(&:token?).each do |attribute| -%>
    add_index :<%= table_name %>, :<%= attribute.index_name %><%= attribute.inject_index_options %>, unique: true
<% end -%>
<% attributes_with_index.each do |attribute| -%>
    add_index :<%= table_name %>, :<%= attribute.index_name %><%= attribute.inject_index_options %>
<% end -%>
This adds the id:false to the create_table method and will add the binary id by default. The original file from Rails can be found here:
This has been changed by this PR
We now can place the migration template override in a better place, next to the activemodel template here: lib/templates/active_record/model/create_table_migration.rb.tt

Written by

Related posts