Passing a block to ActiveRecord create
I submitted a patch for Rails, which has been committed, to allow you to pass a block to the AR create class method. It got a mention on the RailsEnvy podcast in the Living on the Edge section.
It mind sound boring, but it allows you to pretty up the regular code such as creating a new record from the parameters hash to then save it.
Often you might
@person = Person.new(params[:person])
@person.set_status :alive
@person.group = "default"
@person.save
now you can pretty it up with
@person = Person.create(params[:person]) do |p|
p.set_status :alive
p.group = "default"
end
The inner workings are that it creates a new object using the hash and then passes the object into the block for further manipulation. After the block is executed the record is saved and returned.
It can be particularly useful if you have a few protected attributes that you need to set or some instance method you need to execute when you are creating a record. Admittedly the set_status method might best be run as a callback in the model, but you get the idea.
It also works for the array variant of create when you pass in an array of hashes. The code in the block is executed for each record.
So look for it in Rails 2.1 or use it now with Edge.
Footnote: The original patch was actually larger and included the update method as well. Though DHH was not in favour of it, mentioning that the class update method itself may be of dubious value.
1 comment1 Comment so far
Leave a reply

wow this is very awesome. thanks!