Ruby-on-Rails: Understanding the Basics of Active Record - Active Record: Steps to using it
(Page 3 of 4 )
Active Record minimizes the configuration requirements, yet demands that certain conventions be followed. These conventions form part of the steps of working with Active Record. Following are the steps:
1. Creating the table(s)
2. Connecting to the database
3. Creating the ORM
4. Applying CRUD operation
Of these first step is purely convention based. The table has to follow the convention or else one would have to override the default values. Here are the details:
Creating the table(s)
Since convention takes precedence over configuration in RoR, the table has to be created following certain conventions unless you want to override the convention. They are:
- The name of the table should be in its plural form.
- The Primary Key should be name id with the data type as integer.
- If the table references another table, then the Foreign Key should be of the form <referenced table name in singular>_id.
So applying the first two conventions an order tables, SQL script for MySQL would look like:
create table orders (
id int not null auto_increment,
name varchar(100) not null,
/* ... */
primary key (id)
);
Connecting to the database
Just like everything else with RoR, a database connection is also abstracted out. That means an Active Record application makes generic calls, delegating the details to a set of database-specific adapters. To connect to a database, the establish_connection() method of Base class of ActiveRecord has to be called with connection parameters. These parameters differ for different databases. For example the following call creates a connection to a MySQL database called testrails on the server localhost using the given user name and password:
order = Order.find(123)
order.name = "raj" order.save
Delete
Active Record provides the delete method for deleting data. It supports both single row deletion as well as multiple row deletion. The following deletes the record having an id of 20:
Order.delete(123)
And the following deletes the records with ids supplied as a list:
Order.delete([2,3,4,5])
That completes the bird's eye view of how to apply CRUD to an ORM using Active Record. The advanced services provided by Active Record for CRUD will be discussed in the future. In the next section I will be using the services of Active Record along with ActionController and ActionView to create a login module.
Next: Rails in the Real World >>
More Ruby-on-Rails Articles
More By APRajshekhar