Archive for May, 2008
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 commentJeez, where’s your blog dude?
Its time! As Gough Whitlam said. I am finally getting round to starting this blog of mine. At least there are few things which I can actually post about and possibly get some feedback from folks.
This will be my tech blog focussing on, guess what, Ruby and Rails and probably other stuff too. If the name of the blog sounds like I am promoting animal cruelty, fear not, it has its roots in the Ruby community from the mind of the inimitable Why the lucky stiff. And besides I like all the little, little duckies in the pond.
Anyway welcome and I hope to see you round these parts.
PS. If anyone is handy with graphics type software (I am definitely not) and happy to donate time (I know, I’m dreamin) I was thinking of a silhouetted monkey wearing boxing gloves, punching a duck as the main graphic for this blog. Just putting it out there.
No comments
