Книга: Metaprogramming Ruby 2
Назад: Chapter 9: The Design of Active Record
Дальше: How Active Record Is Put Together

A Short Active Record Example

Assume that you already have a file-based SQLite database that follows Active Record’s conventions: this database contains a table called ducks, which has a field called name. You want to map the records in the ducks table to objects of class Duck in your code.

Let’s start by requiring Active Record and opening a connection to the database. (If you want to run this code on your system, you also need to install the SQLite database and the sqlite3 gem. But you can probably follow along fine by just reading the example, without running it.)

 
require ​'active_record'
 
ActiveRecord::Base.establish_connection :adapter => ​"sqlite3"​,
 
:database => ​"dbfile"

Note that in a Rails application, you don’t need to worry about opening the connection; the application reads the names of the adapter and the database from a configuration file, and it calls establish_connection for you. We’re using Active Record on its own here, so we have to open the connection ourselves.

ActiveRecord::Base is the most important class in Active Record. Not only does it contain class methods that do important things, such as opening database connections, it’s also the superclass of all mapped classes, such as Duck:

 
class​ Duck < ActiveRecord::Base
 
validate ​do
 
errors.add(:base, ​"Illegal duck name."​) ​unless​ name[0] == ​'D'
 
end
 
end

The validate method is a Class Macro () that takes a block. You don’t have to worry about the details of the code in the block—just know that in this example, it ensures that a Duck’s name begins with a D. (Our company’s duck-naming policies demand that.) If you try to save a Duck with an illegal name to the database, the save! method will raise an exception, while the more discreet save will fail silently.

By convention, Active Record automatically maps Duck objects to the ducks table. By looking at the database schema, Active Record also finds out that Ducks have a name, and it defines a Ghost Method () to access that field. Thanks to these conventions, you can use the Duck class right away:

 
my_duck = Duck.new
 
my_duck.name = ​"Donald"
 
my_duck.valid? ​# => true
 
my_duck.save!

I’ve checked that my_duck is valid (it begins with a D) and saved it to the database. Reading it back, you get this:

 
duck_from_database = Duck.first
 
duck_from_database.name ​# => "Donald"
 
duck_from_database.delete

That’s enough code for now to give you a sense of how Active Record is meant to be used. Now let’s see what’s happening under the hood.

Назад: Chapter 9: The Design of Active Record
Дальше: How Active Record Is Put Together