aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord/lib
diff options
context:
space:
mode:
authorDavid Heinemeier Hansson <david@loudthinking.com>2008-04-30 23:14:32 -0500
committerDavid Heinemeier Hansson <david@loudthinking.com>2008-04-30 23:14:32 -0500
commitdd120ede53eaf71dee76894998a81626b7a689fc (patch)
treef9bcc98eba07ebfdb662489321b4e1d184020f57 /activerecord/lib
parentc83f75812ef89aea1b8d138aebec25de8057f156 (diff)
downloadrails-dd120ede53eaf71dee76894998a81626b7a689fc.tar.gz
rails-dd120ede53eaf71dee76894998a81626b7a689fc.tar.bz2
rails-dd120ede53eaf71dee76894998a81626b7a689fc.zip
Added block-setting of attributes for Base.create like Base.new already has (Adam Meehan) [#39 state:resolved]
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