This project is archived and is in readonly mode.
Add blocks to AR create and update
Reported by Adam Meehan | April 22nd, 2008 @ 11:24 PM
This patch adds the block syntax to the ActiveRecord class methods create and update.
For example it allows this:
@person = Person.create(params[:person]) do |p|
p.has_rails_patch = false
p.set_status :uncool
end
@person = Person.update(params[:id], params[:person]) do |p|
p.has_rails_patch = true
p.set_status :cool
end
And for the array variants of these methods it will call the block for each record:
Person.create([{:name => 'Matz'}, {:name => 'David'}]) do |p|
p.set_status :cool
end
Both people will be set to cool status.
The create! is also patched.
Tests included.
Thanks,
Adam.
Comments and changes to this ticket
-
Adam Meehan April 23rd, 2008 @ 09:27 AM
Updated patch with conforming more to rails conventions with blocks.
-
matthuhiggins April 27th, 2008 @ 06:53 AM
Perhaps a tangent, but why not replace
object = new(attributes)
yield(object) if block_given?
object.save
object
with
returning new(attributes) do |object|
yield(object) if block_given?
object.save
end
-
Adam Meehan April 27th, 2008 @ 07:24 AM
Sure that would be nice. I was not sure how often 'returning' was being used in rails code. I thought of it more as for external use.
From greping the rails edge code I see there is some use of it. I am happy to change it to the returning convention if thats the way rails is going.
-
Adam Meehan April 27th, 2008 @ 07:36 AM
Added another patch which uses returning. I will let the core team decide what they prefer.
Thanks for the suggestion Matt.
-
matthuhiggins April 27th, 2008 @ 10:38 PM
Using returning reduces performance. Since create is a common operation, my suggestion might not be worth it.
-
Adam Meehan April 27th, 2008 @ 10:46 PM
I did wonder. I will let the core team decide based on what they know and would prefer. Both patches are there.
-
Repository May 1st, 2008 @ 05:14 AM
- State changed from new to resolved
(from [dd120ede53eaf71dee76894998a81626b7a689fc]) Added block-setting of attributes for Base.create like Base.new already has (Adam Meehan) [#39 state:resolved]
-
DHH May 1st, 2008 @ 05:15 AM
- State changed from resolved to new
The create block is good stuff, but I don't think the update one warrants enough use to be included. Base#update is kinda suspect as is.
-
DHH May 1st, 2008 @ 05:15 AM
- State changed from new to resolved
Create your profile
Help contribute to this project by taking a few moments to create your personal profile. Create your profile »
<h2 style="font-size: 14px">Tickets have moved to Github</h2>
The new ticket tracker is available at <a href="https://github.com/rails/rails/issues">https://github.com/rails/rails/issues</a>