Amazon

Friday, February 8, 2008

Rails 2.0, Scaffolding 2.0

I finally took the plunge and upgraded my Rails installation to 2.0.2, the latest as of this post.

I knew from David Heinemeier Hansson's blog that act_as_xxx, paginate, and scaffolding have been relegated to plug-ins, but I did not realize the actual transition would be so rough, as myself and others have come to experience.

I played with the new scaffold generator to see how I might work with it. I came up with the following. I finally decided that I don't like it, and installed the old dynamic scaffolding plug-in (along with the classic pagination plug-in, too). But should you want to stay completely within Rails 2.x, you might find this post handy.

Suppose you want to scaffold the MVC triad for a model named TodoItem. When generating a scaffold you really should supply as many fields as possible. If you supply no fields, the views will be empty, which is pretty much useless.

script/generate scaffold todo_item name:string description:text due_date:datetime completed:boolean


Next, run database migration to get the todo_items table created.

The scaffolded MVC triad will be named TodoItem, todo_items, and todo_items_controller, respectively. Depending on the design for your app, the view and controller names may or may not be appropriate. If not, you'll want to generate your own. For example, you may want the view and controller to be named todo and todo_controller instead.

Then, build up the view and controller you want to keep. You may also create more migrations to modify the database schema as needed. For instance, you might want to add a position column so you can support arbitrary ordering of to-do items.

When you are done, if you have been working on customizing the scaffolded view and controller, you need not do anything else. However, if you've generated and built-up another set of view and controller, you need to destroy the scaffolded ones. But, you want to keep the model. So you'll need to execute the following:

script/destroy scaffold --skip-migration todo_item


The --skip-migration option ensures the migration script that was generated by the scaffold generator isn't deleted.

Now, some may ask why don't I just rename the files. Yes, I could do that. But that seems more troublesome to me, as you will have to change the view directory name, the controller file name, the controller class name, and edit the config/routes.rb file.

Instead, I believe a real solution would be to add the option to specify the controller name back into the scaffold generator. Adding the option to allow the scaffold generator to work off an existing model would be a nice refinement, too.

But, when it's all said and done, I still miss the dynamic scaffolds in Rails 1.x. If you feel as I do, you can read my next post, which will outline how to get the old dynamic scaffolding to work within Rails 2.x.

No comments: