Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Disallow chaining manual .selects + .pluck #1435

Open
blnoonan opened this issue Feb 6, 2025 · 0 comments
Open

Disallow chaining manual .selects + .pluck #1435

blnoonan opened this issue Feb 6, 2025 · 0 comments

Comments

@blnoonan
Copy link

blnoonan commented Feb 6, 2025

Is your feature request related to a problem? Please describe.

In ActiveRecord, chaining a manual .select (.select called with raw SQL) and .pluck produces unexpected results. Examples of this:

  • User.select('id AS id2').pluck(:id2) > Unknown column id2 (issue)
  • User.select('id, email AS user_email').pluck('id', 'user_email') > Unknown column user_email
  • Gift.select("DISTINCT(country_code)").pluck(:country_code) > Results are not de-duped (issue)

And other cases that work can be written more simply:

  • User.select('id').pluck(:id) can be written as User.select(:id).pluck(:id)

The nature of select, which loads up an ActiveRecord::Relation, is incongruous with pluck, which operates on the DB directly. At best the combination can work incidentally, and at worst it can produce silently unexpected results. As stated in the linked rails issue:

pluck selects only what was passed as its arguments (and ignores manual selects)

Describe the solution you'd like

Add a rule to disallow chaining manual selects with pluck. Provide helpful messaging that pluck will ignore the manual directive provided to select.

I am happy to contribute this rule if folks agree it's valuable!

Describe alternatives you've considered

  • Autocorrect .select("RAW").pluck to .select("RAW").to_a.pluck - technically works, but not always desired
  • Disallow this behavior in rails (appears to be a no-go)
  • Disallow any chaining of .select with .pluck - seems valuable, though perhaps overly broad
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant