aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord/lib
diff options
context:
space:
mode:
Diffstat (limited to 'activerecord/lib')
-rwxr-xr-xactiverecord/lib/active_record/base.rb16
-rwxr-xr-xactiverecord/lib/active_record/validations.rb5
2 files changed, 17 insertions, 4 deletions
diff --git a/activerecord/lib/active_record/base.rb b/activerecord/lib/active_record/base.rb
index 63306644fb..4f4ba83a47 100755
--- a/activerecord/lib/active_record/base.rb
+++ b/activerecord/lib/active_record/base.rb
@@ -603,13 +603,25 @@ module ActiveRecord #:nodoc:
# ==== Examples
# # Create a single new object
# User.create(:first_name => 'Jamie')
+ #
# # Create an Array of new objects
# User.create([{:first_name => 'Jamie'}, {:first_name => 'Jeremy'}])
- def create(attributes = nil)
+ #
+ # # Create a single object and pass it into a block to set other attributes.
+ # User.create(:first_name => 'Jamie') do |u|
+ # u.is_admin = false
+ # end
+ #
+ # # Creating an Array of new objects using a block, where the block is executed for each object:
+ # User.create([{:first_name => 'Jamie'}, {:first_name => 'Jeremy'}]) do |u|
+ # u.is_admin = false
+ # end
+ def create(attributes = nil, &block)
if attributes.is_a?(Array)
- attributes.collect { |attr| create(attr) }
+ attributes.collect { |attr| create(attr, &block) }
else
object = new(attributes)
+ yield(object) if block_given?
object.save
object
end
diff --git a/activerecord/lib/active_record/validations.rb b/activerecord/lib/active_record/validations.rb
index 1d12ea8ad7..5ca51c014c 100755
--- a/activerecord/lib/active_record/validations.rb
+++ b/activerecord/lib/active_record/validations.rb
@@ -873,11 +873,12 @@ module ActiveRecord
# Creates an object just like Base.create but calls save! instead of save
# so an exception is raised if the record is invalid.
- def create!(attributes = nil)
+ def create!(attributes = nil, &block)
if attributes.is_a?(Array)
- attributes.collect { |attr| create!(attr) }
+ attributes.collect { |attr| create!(attr, &block) }
else
object = new(attributes)
+ yield(object) if block_given?
object.save!
object
end