Thursday, June 4, 2009

habtm based javascript UI in rails

From the time I have begun web-development in rails it has always been a big struggle to get Models and Views to play well together.
Few examples being, Restricting Views Based on Roles, Search forms in views.

Of course these days with ruby gems like Declarative Authorization , Authlogic, and Searchlogic life is not the same.

Still, as things get complex more, it gets really difficult to create user interfaces to powerfully play with models while following the programming style that rails encourages.
Forget about good CSS looks and Javascript Effects but also coming up with design which flows properly with the web application.

Okay now coming to the point of my rant.
Just today I have finished designing and developing UI which took quite a bit of ruby, javascript and rjs, but in the end was worth it, without having to put in a lot of javascript (unobtrusive or not), and not ending up writing something from scratch.

So here's the problem, there are two models with habtm relationship (dont ask why), now we know the traditional form with either
  1. checkboxes or
  2. collection_select in the form ,
  3. also I came across another solution which was just as I wanted with option transfer select boxes called SwapSelect.
Which was kind of cool, but it was limited in certain things for example, it needed all the options in to construct a big select box, and javascript code was beyond my understanding of javascript or simply put the author did not use any JS library , he wrote the traditional javascript which I am not comfortable coding in.

ok now I wanted the following
  1. A select box on the left with filters to list by name keywords, display only 25 records and then display additional by pagination etc.
  2. A second select box on the right which displays existing options and acts like a container for adding new options from the one on the left.
  3. and buttons in between to add selected to right, add selected to left, add all to right and add all to left options.
Like the following picture

ok the first point a search enabled list of available options was actually the easiest part, this is where I used Searchlogic, which is a brilliant rubygem, now other than that everything was simple javascript using Prototype library, rjs and little ruby.

What happens after the options are final is that I clone the final select box and give it a new name with _ids[] in the end folowing rails convention to make a habtm form object which I attach it to the model's form. and the voila the record updated with a put or created with a post following REST.

The way rails architecture allows you to design this kind of complex simply is what inspired "Me" to write about it.

Soon as I published I saw another article which is very good, and its a plugin too.

No comments:

Post a Comment