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

Relation subqueries #188

Closed
wants to merge 1 commit into from
Closed
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
5 changes: 4 additions & 1 deletion activerecord/lib/active_record/relation/predicate_builder.rb
Expand Up @@ -18,7 +18,10 @@ def self.build_from_hash(engine, attributes, default_table)
attribute = table[column.to_sym] attribute = table[column.to_sym]


case value case value
when Array, ActiveRecord::Associations::AssociationCollection, ActiveRecord::Relation when ActiveRecord::Relation
value.select_values = Array.wrap("#{value.klass.quoted_table_name}.id") if value.select_values.empty?
attribute.in(value.arel.ast)
when Array, ActiveRecord::Associations::AssociationCollection
values = value.to_a.map { |x| values = value.to_a.map { |x|
x.is_a?(ActiveRecord::Base) ? x.id : x x.is_a?(ActiveRecord::Base) ? x.id : x
} }
Expand Down
29 changes: 28 additions & 1 deletion activerecord/test/cases/relations_test.rb
Expand Up @@ -467,7 +467,7 @@ def test_find_by_id_with_list_of_ar
authors = Author.find_by_id([author]) authors = Author.find_by_id([author])
assert_equal author, authors assert_equal author, authors
end end

def test_find_all_using_where_twice_should_or_the_relation def test_find_all_using_where_twice_should_or_the_relation
david = authors(:david) david = authors(:david)
relation = Author.unscoped relation = Author.unscoped
Expand All @@ -488,6 +488,33 @@ def test_find_all_with_multiple_ors
end end
assert_equal [david], relation.all assert_equal [david], relation.all
end end

def test_find_all_using_where_with_relation
david = authors(:david)
# switching the lines below would succeed in current rails
# assert_queries(2) {
assert_queries(1) {
relation = Author.where(:id => Author.where(:id => david.id))
assert_equal [david], relation.all
}
end

def test_find_all_using_where_with_relation_with_joins
david = authors(:david)
assert_queries(1) {
relation = Author.where(:id => Author.joins(:posts).where(:id => david.id))
assert_equal [david], relation.all
}
end


def test_find_all_using_where_with_relation_with_select_to_build_subquery
david = authors(:david)
assert_queries(1) {
relation = Author.where(:name => Author.where(:id => david.id).select(:name))
assert_equal [david], relation.all
}
end


def test_exists def test_exists
davids = Author.where(:name => 'David') davids = Author.where(:name => 'David')
Expand Down