Web development with Ruby on Rails

Pimp My Rails: The First Model

walski_en on 04/15/2008 09.36 AM
(read 3452 times)

So let's get familiar with the last element of the MVC pattern, the model. First of all: We want our data to be persisted somewhere. For that reason it might be a very good idea, to get a database up an running.

Since Rails 2.0 a default Rails application ships with a SQLite 3 database connection. You don't have to edit anything for this, but you need SQLite 3! If you would like to work with MySQL, Postgres or anything else, instead, you can create your application with this command:

rails -d mysql test_application

Then it's unavoidable to configure the database's host, user, password and name in the conf/database.yml file of your application. If you've generated the application with the "-d mysql" flag, as described above there should be a sample of the database.yml in your project, already.

But as long, as you don't have db server installed locally already, we encourage you to stick with the SQLite default, whose installation is described below.

SQLite 3

SQLite 3 is a very easy but nearly full-fledged relational database system like MySQL. But unlike MySQL this don't need a complicated server setup. It safes it's data in files but you can access this data by SQL commands. Not for production, right! But it's excellent to start with, as it needs no special configuration in your Rails project.

Installing

  • Linux: Install sqlite3 with apt
  • Mac: Since Mac OS X Tiger, sqlite3 is installed already. Otherwise use Darwin Ports to install sqlite3
  • Windows: Go to the SQLite webpage and download the 1st and 3rd file of the windows binaries (should be named sqlite-x_y_z.zip and sqlitedll-x_y_z.zip) and unzip them into your to your Ruby bin directory (typically C:/ruby/bin).

Now you just need the sqlite3-ruby gem. Install it with:
sudo gem install sqlite3-ruby
(don't forget to leave out the sudo in windows machines!) and you're done.

Let's create our first model!

script/generate model car

This should generate some files. Right now only two are important for us: db/migrate/001_create_cars.rb and app/models/car.rb .

Migrations

A really cool feature of Rails are the migrations. They are used to define your database. In PHP applications you might just edit the database by phpMyAdmin or something like that. But that can be very painful! If you're working with multiple developers on one project you have to share the database schema with your colleagues and you can never revert a change.
Migrations solve that problem. They are an incremental description of your database. Whenever you generate a new model you'll write an initiative migration of a new table (any model is represented by one table in the db). Whenever you feel, like you should add a column to that table or do anything else with the table, you can write a new migration to just do that. I'll explain all the things you can do later. And if you're done, you just run:
rake db:migrate
in the root of your application and Rails is doing all the changes to the database for you, that are new since you've run rake db:migrate the last time.

The first one is a so called "migration". We will use it to define the table, that represents objects of our new model in the database. So open it up. It should look like this:

class CreateCars < ActiveRecord::Migration

def self.up

create_table :cars do |t|

t.timestamps

end

end

def self.down

drop_table :cars

end

end

There are two methods in this file. The self.up and the self.down method. The up method is called when you would like to migrate your database schema to a higher version. The down method is called, when you would like to revert changes and so migrate your db schema to a lower version. In this case the down method just drops the database, while the up method created the database in line 3. So we need to define which columns we need and what type they are. For our little testing we would like to store three informations in the database, the name of the brand as a string, the top speed and if it has an automatic gearbox or not. So we change the up method, that it looks like that:

def self.up

create_table :cars do |t|

t.string :brand_name

t.integer :top_speed

t.boolean :automatic

t.timestamps

end

end

This will create three columns, named "brand_name", "top_speed" and "automatic". Which type these columns will be in the database is not easy to say. It depends on the db you use and it doesn't matter for us! All we need to know is, that we can use brand_name as a string, top_speed as a non-floating-point number (integer) and automatic as a boolean value. The t.timestamps line is a shortcut which is available since Rails 2.0. It actually creates two extra columns in the database, named "created_at" and "updated_at". Rails is clever and fills those columns, when they are there. So when you create a new object of this model the current time and date will be saved as the created_at value of the object. And whenever you update it, this time and date will be saved as the updated_at value. As you can also see, the name of the table will be "cars". Don't change this! The model relies on THIS name. You can tell it, that it should use another table, but this is inconvenient! Just follow the simple rule: model named with a singular word and the corresponding table is the plural form of this word. And yesssss, Rails knows about some irregular plural forms. If you create a model named "man", the corresponding migration will create a table named "men". And if Rails doesn't know a irregular form, you would like to use, it's possible to add new ones. But you'll have to lookup this one on your own, when you need it.

Now let's tell our db about the changes we would like to make. Go to the root directory of your application and then do this:

rake db:migrate

Now your database should contain the new table. Let's test it with the Rails console. The Rails console is a wonderful tool to explore the power of Ruby and Rails on-the-fly! Just go to your application's root, again and type:

script/console

After it loaded up, you can interact with your Rails application! Just type this:

my_car = Car.create!(:brand_name => 'Volvo', :automatic => true, :top_speed => 150)

If this isn't creating a total mayhem on the console but rather displays something like that:

=> #

you've successfully created your first instance of the Car model! You can try this in the console:

puts my_car.top_speed

This will print out the top speed of the car and should look like this:

>> puts my_car.top_speed
150
=> nil

Cool, seems to work. Now let's try to get this car back from the database. If you're tending to be somehow paranoid, you can close and reopen the Rails console to see, that we're using no tricks ;) Then type this in the console:

another_car = Car.find(:first)
puts another_car.top_speed

This should print 150 like this:

150
=> nil

Great! Everything is working. Unfortunately this got to long, to show you how to do the authentication in this episode. But watch out for the article in the next week, which should give you an introduction to that. So long have fun with your new knowledge and play around with the test application as much as you can. If you're stuck just ask Google, it's able to help you with most of the troubles, you will encounter.

Thanks for your attention,

Thorben

Web development with Ruby on Rails

Pimp My Rails
Pimp My Rails: The Rails Framework
Rails Pimpin' Continues

Share Subscribe

Comments

04/15/2008 05.44 PM

awesome

I'm loving these articles! Keep 'em coming! My knowledge of RoR has included all that you've discussed so far, but it was a nice recap.

I'm waiting for the authentication article and all the others to come!

keep it up!

Add new comment
Please log in to use this feature!
Games
Ninja MMORPG
17540 votes
Khan Wars
8216 votes
Supremacy 1914
3402 votes
Tycoon Online
1207 votes
Bulfleet
661 votes
Orions Belt
308 votes
Crimson Moon Free Online ...
211 votes
Domain of Heroes
204 votes
90-minutes - online football ...
183 votes
ZeldereX Online
107 votes
All Browser Games
Screenshots
MondoZoo
MondoVeto
MondoFoot
Gilfor's...

How old are you?
< 18
18 - 24
25 - 34
35 - 49
> 50