Class: RuboCop::Cop::Rails::CreateTableWithTimestamps

Inherits:
Base
  • Object
show all
Includes:
ActiveRecordMigrationsHelper
Defined in:
lib/rubocop/cop/rails/create_table_with_timestamps.rb

Overview

Checks the migration for which timestamps are not included when creating a new table. In many cases, timestamps are useful information and should be added.

NOTE: Allow ‘timestamps` not written when `id: false` because this emphasizes respecting user’s editing intentions.

Examples:

# bad
create_table :users

# bad
create_table :users do |t|
  t.string :name
  t.string :email
end

# good
create_table :users do |t|
  t.string :name
  t.string :email

  t.timestamps
end

# good
create_table :users do |t|
  t.string :name
  t.string :email

  t.datetime :created_at, default: -> { 'CURRENT_TIMESTAMP' }
end

# good
create_table :users do |t|
  t.string :name
  t.string :email

  t.datetime :updated_at, default: -> { 'CURRENT_TIMESTAMP' }
end

# good
create_table :users, articles, id: false do |t|
  t.integer :user_id
  t.integer :article_id
end

Constant Summary collapse

MSG =
'Add timestamps when creating a new table.'
RESTRICT_ON_SEND =
%i[create_table].freeze

Constants included from ActiveRecordMigrationsHelper

ActiveRecordMigrationsHelper::MYSQL_SCHEMA_DEFINITIONS, ActiveRecordMigrationsHelper::POSTGRES_SCHEMA_DEFINITIONS, ActiveRecordMigrationsHelper::RAILS_ABSTRACT_SCHEMA_DEFINITIONS, ActiveRecordMigrationsHelper::RAILS_ABSTRACT_SCHEMA_DEFINITIONS_HELPERS

Instance Method Summary collapse

Instance Method Details

#on_send(node) ⇒ Object



76
77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/rubocop/cop/rails/create_table_with_timestamps.rb', line 76

def on_send(node)
  return if !node.command?(:create_table) || use_id_false_option?(node)

  parent = node.parent

  if create_table_with_block?(parent)
    add_offense(parent) if parent.body.nil? || !time_columns_included?(parent.body)
  elsif create_table_with_timestamps_proc?(node)
    # nothing to do
  else
    add_offense(node)
  end
end