Behavior

The core Active Record design pattern relies on making CRUD operations available on classes and instances. If you want to work with data from a table, use the class. Methods such as find and count work on a class. If you want to work with a table row, use an instance. Methods such as save, update, and destroy work on instances. ActiveRecord::Base class supplies many of the methods, and method_missing provides most of the rest. You can find the documentation for the latest stable Active Record version online at the following address: http://api.rubyonrails.com.

Finders

Whenever you need to find instances of some type, you will use one of the many forms of finders. The most basic form is ClassName.find(id). The id is an identifier of the instance you need to find. In place of the identifier, you can use :all to find all instances, or :first to find only the first instance. Finders have many options. You can specify the options after the id field in a hash map. Remember, in Ruby, you can omit the braces in your hash map if the hash is the last parameter in your method. You’ll often see Rails developers do this. We’ll walk you through a few of these in Table 3-3, and also in the console.

Table 3-3. Rails finder options

Option

Description

conditions

:conditions => ["name = ?”, name]. Specify conditions in the form of a SQL where clause. If you have input parameters, you can pass an array, where the first element is the condition string and the following elements are the replacement ...

Get Rails: Up and Running, 2nd Edition 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.