Skip to content

Commit

Permalink
Merge pull request #1209 from fatkodima/pluck_in_where-where-not
Browse files Browse the repository at this point in the history
Support `where.not` for `Rails/PluckInWhere`
  • Loading branch information
koic authored Dec 12, 2023
2 parents 2776841 + d9c2a44 commit 1431257
Show file tree
Hide file tree
Showing 4 changed files with 22 additions and 1 deletion.
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

0 comments on commit 1431257

Please sign in to comment.