Permalink
Browse files

automatically add references when we can

  • Loading branch information...
1 parent 4429f16 commit ee7f66603573fd441f1522cc73ec0b7f56c4d1af @jonleighton jonleighton committed Jan 14, 2012
View
12 activerecord/lib/active_record/relation/predicate_builder.rb
@@ -21,6 +21,18 @@ def self.build_from_hash(engine, attributes, default_table)
predicates.flatten
end
+ def self.references(attributes)
+ references = attributes.map do |key, value|
+ if value.is_a?(Hash)
+ key
+ else
+ key = key.to_s
+ key.split('.').first.to_sym if key.include?('.')
+ end
+ end
+ references.compact
+ end
+
private
def self.build(attribute, value)
case value
View
4 activerecord/lib/active_record/relation/query_methods.rb
@@ -52,7 +52,7 @@ def references(*args)
return self if args.blank?
relation = clone
- relation.references_values = (references_values + args).uniq
+ relation.references_values = (references_values + args).flatten.uniq
relation
end
@@ -151,6 +151,7 @@ def where(opts, *rest)
return self if opts.blank?
relation = clone
+ relation = relation.references(PredicateBuilder.references(opts)) if Hash === opts
relation.where_values += build_where(opts, rest)
relation
end
@@ -159,6 +160,7 @@ def having(opts, *rest)
return self if opts.blank?
relation = clone
+ relation = relation.references(PredicateBuilder.references(opts)) if Hash === opts
relation.having_values += build_where(opts, rest)
relation
end
View
14 activerecord/test/cases/relations_test.rb
@@ -1175,4 +1175,18 @@ def test_references_doesnt_trigger_eager_loading_if_reference_not_included
scope = Post.references(:comments)
assert !scope.eager_loading?
end
+
+ def test_automatically_added_references
+ scope = Post.where(:comments => { :body => "Bla" })
+ assert_equal [:comments], scope.references_values
+
+ scope = Post.where('comments.body' => 'Bla')
+ assert_equal [:comments], scope.references_values
+
+ scope = Post.having(:comments => { :body => "Bla" })
+ assert_equal [:comments], scope.references_values
+
+ scope = Post.having('comments.body' => 'Bla')
+ assert_equal [:comments], scope.references_values
+ end
end

0 comments on commit ee7f666

Please sign in to comment.