Lost Password?
Register now!
Page « 1 2 (3) 4 5 6 ... 9 »
Articles : Web Development Using the Ruby on Rails
on 2008/7/27 23:54:31 (2880 reads)

The Model

The model in a database-driven Web application is contained in the database. ActiveRecord lets you 'wrap' a class around each table, to which you can add your own business logic, and voila, you have your own domain model. Let's see how this 'wrapping' happens when we have a table called 'employees' that we want to access. The ActiveRecord class would like this:

class Employee < ActiveRecord::Base

Would you believe it if I said this class lets you access all the columns in the table 'employees' and enables you to read, write, update and delete records? Do you remember the philosophy of 'Convention over Configuration'? This is a very clear example of that principle: it lets you write less code (and fewer bugs). Let's take a look at how this works under the hood.

How does Rails know we are interested in the table 'employees'?

Convention: the name of the model is the singular of the database table name.

How can you access the different columns in the table?

Convention: Rails adds attributes to the Employee class with the same name as the columns in the table. For example, the 'employees' table has a column named 'name', so the Employee class would have a 'name' attribute. The attributes are actually added at runtime, using Ruby's powerful dynamic capabilities, this is why you don't see them in the source code.

All the code required to load/save the data from/to the table is inherited from the ActiveRecord::Base class, all for free! You can add your own business methods to this class if you want.

Storing and loading Employees won't get you very far though. It would be nice if we could define a relation with some other tables. After all, we are working with a 'relational' database. Let's suppose we have an ActiveRecord class 'Company' and a database table 'companies' (remember that the classname is the singular of the tablename). In order for us to be able to ask an Employee object what company he works for, we need to tell Rails that an employee belongs to a company:

class Employee < ActiveRecord::Base
belongs_to :company

If 'employee' is an instance of the Employee class, we can ask it what company is attached to it:

employee = Employee.find_by_name('David Heinemeier Hansson')
# note that Rails has find_by_ method for each column!
puts employee.company # -> 37 Signals

Note: everything after # is considered commentary

Page « 1 2 (3) 4 5 6 ... 9 »
Printer Friendly Page Send this Story to a Friend Create a PDF from the article