Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Rails: Setting a Default Timestamp for a Datetime Column

Rails: Setting a Default Timestamp for a Datetime Column

In Rails 5 we can set a default timestamp for a datetime column using a lambda with 'CURRENT_TIMESTAMP'.

default: -> { 'CURRENT_TIMESTAMP' }

Creating a table:

class CreateTopics < ActiveRecord::Migration[5.1]
  def change
    create_table :topics do |t|
      t.datetime :edited_at, null: false, default: -> { 'CURRENT_TIMESTAMP' }
      t.timestamps
    end
  end 
end

Updating a table:

class AddDefaultToEditedAtInTopics < ActiveRecord::Migration[5.1]
  def change
    change_column :topics,
                  :edited_at,
                  :datetime,
                   null: false,
                   default: -> { 'CURRENT_TIMESTAMP' }
  end
end

Source: https://stackoverflow.com/a/40647191/6212572

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.