Wednesday, August 20, 2014

Ruby on Rails scaffold generated form fields

Rails has a cool feature that generates basic CRUD screens based on command line input. It can generate a model file, a set of views, a controller, tests, and migrations. While officially shunned for production code, scaffolding may produce most of the functionality you need in parts of your application.

It generates views with array style form field names. For example, if your model name is "widget" and it has an attribute of "column1", the form name generated in views will be name="widget[column1]". It may not be immediately clear how to reference this field using params in the controller.

The answer is to reference it as a hash of hashes. A simple name="field" is referenced in the controller as params[:field]. The scaffold generated field in the above example would be referenced as params[:widget][:column1].