Skip to content

Unsafe autocorrect with Rails/Pluck #826

Closed
@axlekb

Description

If column name is aliased in a select clause, using .pluck('alias_column') in place of .map { |post| post['alias_column'] } will cause an ActiveRecord::StatementInvalid

Cop docs:

# bad
Post.published.map { |post| post[:title] }
[{ a: :b, c: :d }].collect { |el| el[:a] }

# good
Post.published.pluck(:title)
[{ a: :b, c: :d }].pluck(:a)

Expected behavior

Autocorrect should not result in changes that raise an error

Actual behavior

Autocorrect causes ActiveRecord::StatementInvalid

Steps to reproduce the problem

  • Add a #join and #select clause to an ActiveRecord::Relation. (e.g. .select("table_1.*", "table_2.id AS table_2_id"))

Using .map { |x| x['table_2_id'] } returns an Array of the aliased column
Using .pluck('table_2_id') raises an ActiveRecord::StatementInvalid because table_2_id is not a table column
Using .to_a.pluck('table_2_id') returns an Array of the aliased column

RuboCop version

$ rubocop -V
1.37.0 (using Parser 3.1.2.1, rubocop-ast 1.23.0, running on ruby 3.0.4) [arm64-darwin21]
  - rubocop-performance 1.15.0
  - rubocop-rails 2.17.0
  - rubocop-rspec 2.13.2

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

enhancementNew feature or request

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions