Skip to content
Browse files

Refactor to remove some duplication

  • Loading branch information...
1 parent eb4a623 commit e588c98035cbb0ab55d9509cf64916b97383ab6e @jonleighton jonleighton committed Sep 12, 2012
View
4 activerecord/lib/active_record/reflection.rb
@@ -358,6 +358,10 @@ def association_class
end
end
+ def polymorphic?
+ options.key? :polymorphic
+ end
+
private
def derive_class_name
class_name = name.to_s.camelize
View
57 activerecord/lib/active_record/relation/predicate_builder.rb
@@ -11,15 +11,7 @@ def self.build_from_hash(engine, attributes, default_table)
association = engine.reflect_on_association(column.to_sym)
value.each do |k, v|
- if association && rk = find_reflection_key(k, association.klass, v)
- if rk[:foreign_type]
- queries << build(table[rk[:foreign_type]], v.class.base_class)
- end
-
- k = rk[:foreign_key]
- end
-
- queries << build(table[k.to_sym], v)
+ queries.concat expand(association && association.klass, table, k, v)
end
else
column = column.to_s
@@ -29,18 +21,30 @@ def self.build_from_hash(engine, attributes, default_table)
table = Arel::Table.new(table_name, engine)
end
- if rk = find_reflection_key(column, engine, value)
- if rk[:foreign_type]
- queries << build(table[rk[:foreign_type]], value.class.base_class)
- end
+ queries.concat expand(engine, table, column, value)
+ end
+ end
- column = rk[:foreign_key]
- end
+ queries
+ end
- queries << build(table[column.to_sym], value)
+ def self.expand(klass, table, column, value)
+ queries = []
+
+ # Find the foreign key when using queries such as:
+ # Post.where(:author => author)
+ #
+ # For polymorphic relationships, find the foreign key and type:
+ # PriceEstimate.where(:estimate_of => treasure)
+ if klass && value.class < Model::Tag && reflection = klass.reflect_on_association(column.to_sym)
+ if reflection.polymorphic?
+ queries << build(table[reflection.foreign_type], value.class.base_class)
end
+
+ column = reflection.foreign_key
end
+ queries << build(table[column.to_sym], value)
queries
end
@@ -55,27 +59,6 @@ def self.references(attributes)
end.compact
end
- # Find the foreign key when using queries such as:
- # Post.where(:author => author)
- #
- # For polymorphic relationships, find the foreign key and type:
- # PriceEstimate.where(:estimate_of => treasure)
- def self.find_reflection_key(parent_column, model, value)
- # value must be an ActiveRecord object
- return nil unless value.class < Model::Tag
-
- if reflection = model.reflections[parent_column.to_sym]
- if reflection.options[:polymorphic]
- {
- :foreign_key => reflection.foreign_key,
- :foreign_type => reflection.foreign_type
- }
- else
- { :foreign_key => reflection.foreign_key }
- end
- end
- end
-
private
def self.build(attribute, value)
case value

0 comments on commit e588c98

Please sign in to comment.
Something went wrong with that request. Please try again.