In this conclusion to a four-part article series on building a basic Ruby-on-Rails application, you'll learn how to add validations, build the basic scaffolding, and more. This article is excerpted from chapter three of the book Beginning Rails: From Novice to Professional, written by Jeffery Allan Hardy, Cloves Carneiro Jr. and Hampton Catlin (Apress; ISBN: 1590596862).
Finishing a Basic Ruby-on-Rails Application (Page 1 of 3 )
Adding More Fields
Now that you can see the model represented in the browser, we think it would be a good idea to add some more fields to make it a little more interesting. Whenever you need to add or modify database fields, you should do so using a migration. In this case, we’ll add the urlanddescriptionfields to theeventstable.
We didn’t need to generate the last migration (the one that we used to create theeventstable), because the model generator took care of that for us. This time around, we’ll use the migration generator. It works just like the model and controller generators, which you’ve already seen in action. All you need to do is give the migration generator a descriptive name for the transformation.
As you’ve already seen, the generator creates a migration class indb/migrateprefixed by its number in the queue. In this case, since this is our second migration, the prefix is 002. If you open the migration file, you’ll see that it’s just an empty stub. Unlike with the model generator, which prefilled the migration to some extent, we’ll need to add the information manually here. To do this, use theadd_columnmethod with arguments.
class AddUrlAndDescriptionToEvents < ActiveRecord::Migration def self.up add_column :events, :url, :string add_column :events, :description, :text end
def self.down remove_column :events, :url remove_column :events, :description end end
The first argument is the table name (events), the second is the field name, and the third is the field type. You’ll also want to fill in theself.downmethod to reverse the changes that this migration will make. While it’s unlikely at this point that you’ll want to remove these fields, it’s a good idea to maintain reversibility. Theremove_columnmethod is the opposite ofadd_column. The only difference in its arguments is that you don’t need to specify the field type.
With this new migration in place, use the Rake task to apply it and make the changes to the database.
If all went according to plan, youreventstable will have two new fields. Now, here comes the fun part. Make sure your web server is still running and try adding a new event. Presto! Rails knows about the new fields, as you can see in Figure 3-4.
Figure 3-4. Additional fields added to the new event form
This exposes the central advantage of this type of scaffolding: you don’t need to generate new versions of the scaffold files as your domain model evolves. Because the scaffold is generated dynamically at runtime, it’s always a fresh representation of the fields in your table.