Ruby-on-Rails

Database for a Ruby-on-Rails Application

In this second part of a four-part article series on building a basic Ruby-on-Rails application, you will learn how to create both a database and the event model. 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).

Now that we can connect to the database, we’re going to create a model. Remember that models in Rails correspond to database table names. Since we want to model events, we’re going to create a model named Event. By convention, model names are singular and correspond to plural table names. So, anEventmodel will expect a table namedevents; aPersonmodel will expect a table namedpeople.

Like most things in Rails, models have their own generator script that makes it easier to get started. The generator will automatically create a new model file in theapp/modelsdirectory, and will create a bunch of other files to boot. Among these are a unit test (for testing your model’s functionality, as we’ll discuss in Chapter 9) and a database migration. A database migration contains instructions for building the database table and the fields to create. Whenever you generate a new model, a migration will be created along with it.

Note If you want to skip generation of the migration when generating a new model, you can pass the--skip-migration argument to the generator.

As you can see from the usage banner, the generator takes a model name as its argument. The model name may be given in CamelCase or under_score format, and options can be provided if you want to automatically populate the resulting migration with column information.

If you look at the lines that start withcreate, you’ll see that the generator created an event model, an event test, an events fixture (which is a textual representation of table data that you can use for testing), and a migration named001_create_events.rb. With that, our model is generated.

Please check back for the continuation of this article.

DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.