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 include? and member? on composite primary key relations #48761

Merged
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
7 changes: 6 additions & 1 deletion activerecord/lib/active_record/relation/finder_methods.rb
Expand Up @@ -355,7 +355,12 @@ def include?(record)
if loaded? || offset_value || limit_value || having_clause.any?
records.include?(record)
else
record.is_a?(klass) && exists?(record.id)
id = if record.class.composite_primary_key?
record.class.primary_key.zip(record.id).to_h
else
record.id
end
record.is_a?(klass) && exists?(id)
end
end

Expand Down
32 changes: 32 additions & 0 deletions activerecord/test/cases/finder_test.rb
Expand Up @@ -475,6 +475,22 @@ def test_include_on_loaded_relation_without_match
end
end

def test_include_on_unloaded_relation_with_composite_primary_key
assert_sql(/1 AS one.*LIMIT/) do
book = cpk_books(:cpk_great_author_first_book)
assert Cpk::Book.where(title: "The first book").include?(book)
end
end

def test_include_on_loaded_relation_with_composite_primary_key
books = Cpk::Book.where(title: "The first book").load
great_author_book = cpk_books(:cpk_great_author_first_book)

assert_no_queries do
assert books.include?(great_author_book)
end
end

def test_member_on_unloaded_relation_with_match
assert_sql(/1 AS one.*LIMIT/) do
assert_equal true, Customer.where(name: "David").member?(customers(:david))
Expand Down Expand Up @@ -530,6 +546,22 @@ def test_member_on_loaded_relation_without_match
end
end

def test_member_on_unloaded_relation_with_composite_primary_key
assert_sql(/1 AS one.*LIMIT/) do
book = cpk_books(:cpk_great_author_first_book)
assert Cpk::Book.where(title: "The first book").member?(book)
end
end

def test_member_on_loaded_relation_with_composite_primary_key
books = Cpk::Book.where(title: "The first book").load
great_author_book = cpk_books(:cpk_great_author_first_book)

assert_no_queries do
assert books.member?(great_author_book)
end
end

def test_find_by_array_of_one_id
assert_kind_of(Array, Topic.find([ 1 ]))
assert_equal(1, Topic.find([ 1 ]).length)
Expand Down