Merge pull request #30126 from chopraanmol1/support_for_has_many_and_has_one_for_where_relation

Fixed query building when relation is passed for has one or has many association in where
This commit is contained in:
Rafael França 2017-08-11 17:58:02 -04:00 committed by GitHub
commit 5834d2f5d9
4 changed files with 26 additions and 12 deletions

View File

@ -305,13 +305,17 @@ module ActiveRecord
end
def get_join_keys(association_klass)
JoinKeys.new(join_pk(association_klass), join_fk)
JoinKeys.new(join_pk(association_klass), join_foreign_key)
end
def build_scope(table, predicate_builder = predicate_builder(table))
Relation.create(klass, table, predicate_builder)
end
def join_foreign_key
active_record_primary_key
end
protected
def actual_source_reflection # FIXME: this is a horrible name
self
@ -325,10 +329,6 @@ module ActiveRecord
def join_pk(_)
foreign_key
end
def join_fk
active_record_primary_key
end
end
# Base class for AggregateReflection and AssociationReflection. Objects of
@ -754,16 +754,16 @@ module ActiveRecord
owner[foreign_key]
end
def join_foreign_key
foreign_key
end
private
def calculate_constructable(macro, options)
!polymorphic?
end
def join_fk
foreign_key
end
def join_pk(klass)
polymorphic? ? association_primary_key(klass) : association_primary_key
end

View File

@ -9,7 +9,7 @@ module ActiveRecord
end
def queries
[associated_table.association_foreign_key.to_s => ids]
[associated_table.association_join_foreign_key.to_s => ids]
end
# TODO Change this to private once we've dropped Ruby 2.2 support.
@ -30,7 +30,7 @@ module ActiveRecord
end
def primary_key
associated_table.association_primary_key
associated_table.association_join_keys.key
end
def convert_to_id(value)

View File

@ -2,7 +2,7 @@
module ActiveRecord
class TableMetadata # :nodoc:
delegate :foreign_type, :foreign_key, to: :association, prefix: true
delegate :foreign_type, :foreign_key, :join_keys, :join_foreign_key, to: :association, prefix: true
delegate :association_primary_key, to: :association
def initialize(klass, arel_table, association = nil)

View File

@ -295,6 +295,20 @@ module ActiveRecord
assert_equal essays(:david_modest_proposal), essay
end
def test_where_with_relation_on_has_many_association
essay = essays(:david_modest_proposal)
author = Author.where(essays: Essay.where(id: essay.id)).first
assert_equal authors(:david), author
end
def test_where_with_relation_on_has_one_association
author = authors(:david)
author_address = AuthorAddress.where(author: Author.where(id: author.id)).first
assert_equal author_addresses(:david_address), author_address
end
def test_where_on_association_with_select_relation
essay = Essay.where(author: Author.where(name: "David").select(:name)).take
assert_equal essays(:david_modest_proposal), essay