Attributes
We use the term metaprogramming often in this book, and now youâve seen it in action. In this case, metaprogramming means that Active Record adds attributes and methods to your code based on the structure of the database without you writing any code. In the end, youâll code far less, but youâll have to work a little harder to understand the magic that goes on under the covers. Once you understand how Active Record works, you will know exactly what attributes and methods your model supports. And thatâs the secret to using Active Record.
Columns
Letâs review what happens when Ruby loads the Photo
class. The Photo
class inherits from the ActiveRecord::Base
class. When that class
loads from the class name Photo
,
Active Record infers that the class wraps a database table named
photos
. Base
then queries SQLite to retrieve
information about the photos
table,
including the definition of each of the columns in that table. Next,
Base
saves the definition of each
column into the @@columns
class
variable. (A class variable has a single value that all instances of the
class share.) @@columns
is an array
of Column
objects, with each column
having these attributes:
- name
The name of the database column.
- type
The Ruby type of the attribute this column will generate.
- number
A Boolean value thatâs
true
if the columnâs data is numeric. Youâll access it through the accessor methodnumber?
.- limit
The maximum size of the data element. For example, for a database column of type
varchar(45) ...
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.