From 3773aa4fbba86184a1f45feebaf72ed4f2702fe7 Mon Sep 17 00:00:00 2001 From: Andrew White Date: Tue, 17 May 2011 22:15:47 +0100 Subject: Add block setting of attributes to singular associations --- .../associations/builder/singular_association.rb | 12 ++++++------ .../lib/active_record/associations/singular_association.rb | 11 ++++++----- 2 files changed, 12 insertions(+), 11 deletions(-) (limited to 'activerecord/lib') diff --git a/activerecord/lib/active_record/associations/builder/singular_association.rb b/activerecord/lib/active_record/associations/builder/singular_association.rb index 62d48d3a2c..638a2ec72a 100644 --- a/activerecord/lib/active_record/associations/builder/singular_association.rb +++ b/activerecord/lib/active_record/associations/builder/singular_association.rb @@ -29,16 +29,16 @@ module ActiveRecord::Associations::Builder def define_constructors name = self.name - model.redefine_method("build_#{name}") do |*params| - association(name).build(*params) + model.redefine_method("build_#{name}") do |*params, &block| + association(name).build(*params, &block) end - model.redefine_method("create_#{name}") do |*params| - association(name).create(*params) + model.redefine_method("create_#{name}") do |*params, &block| + association(name).create(*params, &block) end - model.redefine_method("create_#{name}!") do |*params| - association(name).create!(*params) + model.redefine_method("create_#{name}!") do |*params, &block| + association(name).create!(*params, &block) end end end diff --git a/activerecord/lib/active_record/associations/singular_association.rb b/activerecord/lib/active_record/associations/singular_association.rb index 44dbe984d4..68fe0bde76 100644 --- a/activerecord/lib/active_record/associations/singular_association.rb +++ b/activerecord/lib/active_record/associations/singular_association.rb @@ -17,17 +17,18 @@ module ActiveRecord replace(record) end - def create(attributes = {}, options = {}) - build(attributes, options).tap { |record| record.save } + def create(attributes = {}, options = {}, &block) + build(attributes, options, &block).tap { |record| record.save } end - def create!(attributes = {}, options = {}) - build(attributes, options).tap { |record| record.save! } + def create!(attributes = {}, options = {}, &block) + build(attributes, options, &block).tap { |record| record.save! } end - def build(attributes = {}, options = {}) + def build(attributes = {}, options = {}, &block) record = reflection.build_association(attributes, options) record.assign_attributes(create_scope.except(*record.changed), :without_protection => true) + yield(record) if block_given? set_new_record(record) record end -- cgit v1.2.3