General
"That's clever" moments in Rails
Given that for the past two-plus years my full-time job has been largely as a designer and front-end developer with bits of back-end coding here and there, I haven't been able to keep fully apace with the huge improvements made to Rails since about Rails 2.1. That only a couple of major point versions ago, but a LOT has changed in that time, largely for the better.
All this is leading to the fact that when I do find time to do some Rails development in my spare time, there'll be the occasional bit of cleverness that didn't exist last time I tried to do the same thing. Such a moment got me tonight, as I'm prototyping a new app and wanted a multiple-select list in a form for a model's has_and_belongs_to_many relationship.
I'm used to having to do a bit of manual work for this kind of scenario, so I created an attr_reader on the model called :category_ids and a bit of code in the before_save to cycle through that list of IDs that would be coming through from the form and assign them as the categories for that item.
A quick form post and the correct database records were created, but I noticed that the reloaded form on the page still had the categories I'd chosen in the form selected. Navigating away and coming back showed them still to be there. In the source they were even specifically selected, which surprised me as I hadn't told them to be.
A quick search on the old Google though, and it became clear that Rails now does the obvious for you and creates the category_ids attribute for you and from there the form helpers work their magic.
So the 4 lines of code I'd written in the model weren't necessary - it Just Works™.
That's clever.
Well OK, it's not particularly - it's obviously something that developers hit often enough to be pulled up into the framework and avoid repetition of code - but it's little things like this that make me love Rails.