diff --git a/changelog/fix_an_error_for_rails_select_map.md b/changelog/fix_an_error_for_rails_select_map.md new file mode 100644 index 0000000000..7eab352547 --- /dev/null +++ b/changelog/fix_an_error_for_rails_select_map.md @@ -0,0 +1 @@ +* [#1121](https://github.com/rubocop/rubocop-rails/issues/1121): Fix an error for `Rails/SelectMap` when using `select(:column_name).map(&:column_name)` without receiver model. ([@koic][]) diff --git a/lib/rubocop/cop/rails/select_map.rb b/lib/rubocop/cop/rails/select_map.rb index 54a898385a..ede846d915 100644 --- a/lib/rubocop/cop/rails/select_map.rb +++ b/lib/rubocop/cop/rails/select_map.rb @@ -51,10 +51,13 @@ def find_select_node(node, column_name) end end + # rubocop:disable Metrics/AbcSize def autocorrect(corrector, select_node, node, preferred_method) - corrector.remove(select_node.loc.dot.begin.join(select_node.source_range.end)) + corrector.remove(select_node.loc.dot || node.loc.dot) + corrector.remove(select_node.loc.selector.begin.join(select_node.source_range.end)) corrector.replace(node.loc.selector.begin.join(node.source_range.end), preferred_method) end + # rubocop:enable Metrics/AbcSize def match_column_name?(select_candidate, column_name) return false unless select_candidate.arguments.one? diff --git a/spec/rubocop/cop/rails/select_map_spec.rb b/spec/rubocop/cop/rails/select_map_spec.rb index 0ea548620e..767516e4d6 100644 --- a/spec/rubocop/cop/rails/select_map_spec.rb +++ b/spec/rubocop/cop/rails/select_map_spec.rb @@ -45,6 +45,17 @@ RUBY end + it 'registers an offense when using `select(:column_name).map(&:column_name)` without receiver model' do + expect_offense(<<~RUBY) + select(:column_name).map(&:column_name) + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `pluck(:column_name)` instead of `select` with `map`. + RUBY + + expect_correction(<<~RUBY) + pluck(:column_name) + RUBY + end + it 'does not register an offense when using `select(:mismatch_column_name).map(&:column_name)`' do expect_no_offenses(<<~RUBY) Model.select(:mismatch_column_name).map(&:column_name)