Permalink
Browse files

Refactor the code for singular association constructors. This will al…

…low me to define a create_association! method in a minute.
  • Loading branch information...
1 parent f4a88e8 commit d88caa6e4a8f0f64601fc8bf07b61b682263d712 @jonleighton jonleighton committed with tenderlove Jan 9, 2011
Showing with 13 additions and 8 deletions.
  1. +13 −8 activerecord/lib/active_record/associations.rb
View
21 activerecord/lib/active_record/associations.rb
@@ -1132,8 +1132,7 @@ def has_one(association_id, options = {})
reflection = create_has_one_through_reflection(association_id, options)
else
reflection = create_has_one_reflection(association_id, options)
- association_constructor_method(:build, reflection)
- association_constructor_method(:create, reflection)
+ association_constructor_methods(reflection)
configure_dependency_for_has_one(reflection)
end
association_accessor_methods(reflection)
@@ -1256,8 +1255,7 @@ def belongs_to(association_id, options = {})
association_accessor_methods(reflection)
unless reflection.options[:polymorphic]
- association_constructor_method(:build, reflection)
- association_constructor_method(:create, reflection)
+ association_constructor_methods(reflection)
end
add_counter_cache_callbacks(reflection) if options[:counter_cache]
@@ -1533,10 +1531,17 @@ def collection_accessor_methods(reflection, writer = true)
end
end
- def association_constructor_method(constructor, reflection)
- redefine_method("#{constructor}_#{reflection.name}") do |*params|
- attributes = params.first unless params.empty?
- association_proxy(reflection.name).send(constructor, attributes)
+ def association_constructor_methods(reflection)
+ constructors = {
+ "build_#{reflection.name}" => "build",
+ "create_#{reflection.name}" => "create"
+ }
+
+ constructors.each do |name, proxy_name|
+ redefine_method(name) do |*params|
+ attributes = params.first unless params.empty?
+ association_proxy(reflection.name).send(proxy_name, attributes)
+ end
end
end

0 comments on commit d88caa6

Please sign in to comment.