Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save trevorrjohn/d1501475c3947341c761723f608d495c to your computer and use it in GitHub Desktop.
Save trevorrjohn/d1501475c3947341c761723f608d495c to your computer and use it in GitHub Desktop.
Set default timestamp when generating new model

Many times I want to always set the timestamps when a model is created. At times you will want to create a model in sql only for it to fail because you forgot to set the created_at and updated_at columns to some value. By setting a sane default you will avoid having to think about this in the future.

In your Rails application, copy the code below and paste it in the following file: lib/templates/active_record/migration/create_table_migration.rb.tt

class <%= migration_class_name %> < ActiveRecord::Migration[<%= ActiveRecord::Migration.current_version %>]
  def change
    create_table :<%= table_name %><%= primary_key_type %> do |t|
<% 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 -%>
<% unless attributes.empty? -%>

<% end -%>
<% if options[:timestamps] -%>
      t.timestamps default: -> { "CURRENT_TIMESTAMP" }
<% end -%>
    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 -%>
  end
end

Note:

Where does the template come from?

The content of the template above was copied from activerecord/lib/rails/generators/active_record/migration/templates/create_table_migration.rb.tt

Why that file name?

The Rails model generator will look for the create_table_migration.rb.tt file in the source paths which looks in the following paths (source_paths)

["/path/to/your/app/lib/templates/active_record/model",
 "/path/to/your/app/lib/templates/active_record/migration",
 "/path/to/activerecord-gem/lib/rails/generators/active_record/migration/templates",
 "/Upath/to/activerecord-gem/lib/rails/generators/active_record/model/templates"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment