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

Support where.not for Rails/PluckInWhere #1209

Merged
merged 1 commit into from
Dec 12, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog/change_support_where_not_for_pluck_in_where.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#1198](https://github.com/rubocop/rubocop-rails/issues/1198): Support `where.not` for `Rails/PluckInWhere`. ([@fatkodima][])
9 changes: 8 additions & 1 deletion lib/rubocop/cop/mixin/active_record_helper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,14 @@ def polymorphic?(belongs_to)

def in_where?(node)
send_node = node.each_ancestor(:send).first
send_node && WHERE_METHODS.include?(send_node.method_name)
return false unless send_node

return true if WHERE_METHODS.include?(send_node.method_name)

receiver = send_node.receiver
return false unless receiver&.send_type?

send_node.method?(:not) && WHERE_METHODS.include?(receiver.method_name)
end
end
end
Expand Down
2 changes: 2 additions & 0 deletions lib/rubocop/cop/rails/pluck_in_where.rb
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,12 @@ module Rails
# @example
# # bad
# Post.where(user_id: User.active.pluck(:id))
# Post.where.not(user_id: User.active.pluck(:id))
#
# # good
# Post.where(user_id: User.active.select(:id))
# Post.where(user_id: active_users.select(:id))
# Post.where.not(user_id: active_users.select(:id))
#
# @example EnforcedStyle: conservative (default)
# # good
Expand Down
11 changes: 11 additions & 0 deletions spec/rubocop/cop/rails/pluck_in_where_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,17 @@
RUBY
end

it 'registers an offense and corrects when using `pluck` in `where.not` for constant' do
expect_offense(<<~RUBY)
Post.where.not(user_id: User.active.pluck(:id))
^^^^^ Use `select` instead of `pluck` within `where` query method.
RUBY

expect_correction(<<~RUBY)
Post.where.not(user_id: User.active.select(:id))
RUBY
end

it 'registers an offense and corrects when using `pluck` in `rewhere` for constant' do
expect_offense(<<~RUBY)
Post.rewhere('user_id IN (?)', User.active.pluck(:id))
Expand Down