Skip to content

Commit

Permalink
Support where.not for Rails/PluckInWhere
Browse files Browse the repository at this point in the history
  • Loading branch information
fatkodima committed Dec 12, 2023
1 parent 2776841 commit d9c2a44
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 d9c2a44

Please sign in to comment.