Skip to content

Commit 1d59a6d

Browse files
authored
Merge pull request #975 from koic/allow_create_table_with_timestamps_for_id_false
[Fix #34] Allow `CreateTableWithTimestamps` when using `id: false` and not include `timestamps`
2 parents 26872d6 + 95145a5 commit 1d59a6d

File tree

3 files changed

+26
-3
lines changed

3 files changed

+26
-3
lines changed
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
* [#34](https://github.com/rubocop/rubocop-rails/issues/34): Allow `CreateTableWithTimestamps` when using `id: false` and not include `timestamps`. ([@koic][])

lib/rubocop/cop/rails/create_table_with_timestamps.rb

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,12 @@
33
module RuboCop
44
module Cop
55
module Rails
6-
# Checks the migration for which timestamps are not included
7-
# when creating a new table.
6+
# Checks the migration for which timestamps are not included when creating a new table.
87
# In many cases, timestamps are useful information and should be added.
98
#
9+
# NOTE: Allow `timestamps` not written when `id: false` because this emphasizes respecting
10+
# user's editing intentions.
11+
#
1012
# @example
1113
# # bad
1214
# create_table :users
@@ -40,12 +42,23 @@ module Rails
4042
#
4143
# t.datetime :updated_at, default: -> { 'CURRENT_TIMESTAMP' }
4244
# end
45+
#
46+
# # good
47+
# create_table :users, articles, id: false do |t|
48+
# t.integer :user_id
49+
# t.integer :article_id
50+
# end
51+
#
4352
class CreateTableWithTimestamps < Base
4453
include ActiveRecordMigrationsHelper
4554

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

58+
def_node_search :use_id_false_option?, <<~PATTERN
59+
(pair (sym :id) (false))
60+
PATTERN
61+
4962
def_node_matcher :create_table_with_timestamps_proc?, <<~PATTERN
5063
(send nil? :create_table (sym _) ... (block-pass (sym :timestamps)))
5164
PATTERN
@@ -61,7 +74,7 @@ class CreateTableWithTimestamps < Base
6174
PATTERN
6275

6376
def on_send(node)
64-
return unless node.command?(:create_table)
77+
return if !node.command?(:create_table) || use_id_false_option?(node)
6578

6679
parent = node.parent
6780

spec/rubocop/cop/rails/create_table_with_timestamps_spec.rb

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,4 +108,13 @@
108108
end
109109
RUBY
110110
end
111+
112+
it 'does not register an offense when using `id: false` option and not including `timestamps` in block' do
113+
expect_no_offenses(<<~RUBY)
114+
create_table :users, :articles, id: false do |t|
115+
t.integer :user_id
116+
t.integer :article_id
117+
end
118+
RUBY
119+
end
111120
end

0 commit comments

Comments
 (0)