Introducing ActiveRecord

The ActiveRecord[50] library was born in the Ruby on Rails framework, but it’s easy to use it from stand-alone Ruby code to talk to any existing database. For example, if we had an accounts table with the following data in it:

id

number

balance

1

1765

80

2

2214

250

then we could query that database table using the following Ruby code:

 
>> account = Account.find_by_number(2214)
 
>> puts account.balance
 
=> 250

Similarly, to add a new row to the table, we could do this:

 
new_account = Account.create!(:number => 1234, :amount => 0)

We still need to define this Account class, but the clever thing is, we don’t need to define the database columns in the code. Here’s how the class is defined:

 
class​ Account < ActiveRecord::Base
 
end

That’s it! ActiveRecord examines the database schema and sprinkles a little bit of Ruby’s metaprogramming magic to dynamically extend the Account class with attribute accessor methods, each representing a column in the database table. It even creates special class methods like find_by_number for searching for rows by a particular field. All we have to do is inherit from ActiveRecord::Base, and ActiveRecord does the rest.

How does it know which table to look at? ActiveRecord espouses a principle of convention over configuration. This means that the expected name for the database table represented by the Account ActiveRecord class is accounts; if the table were named widgets, we’d call the class Widget. As long as we stick to those conventions, we get a lot of very useful behavior for very little code.

Managing Schema Changes with Migrations

ActiveRecord also provides a mechanism for dealing with changes to your database schema, which is great when you’re developing a database. Each incremental change to the schema is defined in a migration script. Each migration has a unique version number, and ActiveRecord stores these version numbers in a special table (schema_migrations) as they are applied to the database, meaning it can always tell which migrations need to be applied to bring a schema up-to-date. For more about migrations, check the documentation.[51]

Now you have some grounding in ActiveRecord, let’s get our hands dirty and start adding it to our banking system.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.218.224.226