O'Reilly logo

The Cucumber Book, 2nd Edition by Steve Tooke, Aslak Hellesoy, Matt Wynne

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Introducing ActiveRecord

The ActiveRecord[48] 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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required