Skip to content

Commit

Permalink
Add composite key support to Model.exists?
Browse files Browse the repository at this point in the history
  • Loading branch information
JoeDupuis committed Mar 12, 2024
1 parent 4d3e291 commit f9f3350
Show file tree
Hide file tree
Showing 2 changed files with 4 additions and 2 deletions.
3 changes: 1 addition & 2 deletions activerecord/lib/active_record/relation/finder_methods.rb
Original file line number Diff line number Diff line change
Expand Up @@ -444,8 +444,7 @@ def construct_relation_for_exists(conditions)
relation = except(:select, :distinct, :order)._select!(ONE_AS_ONE).limit!(1)
end

case conditions
when Array, Hash
if conditions.is_a?(Array) && !conditions.first.is_a?(Array) || conditions.is_a?(Hash)
relation.where!(conditions) unless conditions.empty?
else
relation.where!(primary_key => conditions) unless conditions == :none
Expand Down
3 changes: 3 additions & 0 deletions activerecord/test/cases/finder_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -195,11 +195,14 @@ def test_exists
assert_equal true, Topic.exists?(author_name: "Mary", approved: true)
assert_equal true, Topic.exists?(["parent_id = ?", 1])
assert_equal true, Topic.exists?(id: [1, 9999])
assert_equal true, Cpk::Book.exists?([cpk_books(:cpk_great_author_first_book).id])

assert_equal false, Topic.exists?(45)
assert_equal false, Topic.exists?(9999999999999999999999999999999)
assert_equal false, Topic.exists?(Topic.new.id)
assert_equal false, Cpk::Book.exists?([Cpk::Book.new.id])

assert_raises(ArgumentError) { Cpk::Book.exists?(cpk_books(:cpk_great_author_first_book).id) }
assert_raise(ArgumentError) { Topic.exists?([1, 2]) }
end

Expand Down

0 comments on commit f9f3350

Please sign in to comment.