This post originated from an RSS feed registered with Ruby Buzz
by Eric Stewart.
Original Post: Ajax Scaffold Generator for Rails
Feed Title: Ponderings On Ruby
Feed URL: http://blog.eric-stewart.com/category/programming-ruby.rss
Feed Description: This is the Ruby related section of Eric Stewart's weblog. These entries will be the commentary of a long time Java/C++ programmer that started exploring Ruby in 2003.
Richard White has released the latest version of his Ajax Scaffold Generator for Rails. Since I have been heads down on a mostly non-Ajax application until recently I had missed this.
If you appreciate the value of scaffolding in helping you get going in a Rails project and you want to use ajax in your application, this is a very handy way start. It also is a nice way of just generating some code you can play with if you are new to Ajax and want to quickly be able to experiment. And it doesn’t look bad. What is generated looks nice, seems to work well, and might not be too far from production ready depending on your application.
I did perform an accidental experiment. I had previously generated scaffolding for a model/controller in my test project and and re-generated scaffolding using this new ajax generator. All worked well, but I ended up with tests that were testing the original non-ajax scaffold methods. The action methods are just about the same, but they now are designed to only be called via ajax calls. My original functional tests for the controller broke. Enter redirect_or_render.
With Courtenay’s helpful method, it’s pretty easy to get this tests passing again and have these controller actions now support ajax or non-ajax calls. For example, consider the ajax generator created scaffold method create on my sample controller for objects called Tasks:
This method expects to be called via xhr request and only needs to return a snippet of code. If we apply redirect_or_render the action becomes something like:
Now the create action can be called directly as well via a normal request and still function as expected. Note that there is still a bit of work to be done in this case, since we’d really like to have the action render the new action template again so we can show validation errors on the Task. So for these cases, maybe a render_or_xhr_render method would be useful.