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 ... |
Get The Cucumber Book now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.