Prev | Current Page 85 | Next

Kevin Marshall, Chad Pytel, and Jon Yurek

"Pro Active Record: Databases with Ruby and Rails"


All configuration options for a relationship occur within the Active Record class definitions
themselves. For our Account class, we want to add a relationship to a Role object, so we can tell
what type of account we have on our hands. We start off by manually defining our roles table
within our database:
Roles table
id field (integer; auto-incremented; primary key)
name field (text type field)
description field (text type field)
We want our account class to hold the reference to the account??™s role, and we want the
foreign key (the column in one table that points to the ID of a row in another) to be in the accounts
table. So we define this relationship of roles to accounts in our account model with the belongs_to
method. First, we add our Role class definition:
CHAPTER 1 ?–  INTRODUCING ACTIVE RECORD 22
class Role < ActiveRecord::Base
end
Next, we modify our definition of the Account class as follows:
class Account < ActiveRecord::Base
belongs_to :role
end
With those new class definitions we now have a unidirectional relationship between
Account and Role.


Pages:
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97