Prev | Current Page 232 | Next

Kevin Marshall, Chad Pytel, and Jon Yurek

"Pro Active Record: Databases with Ruby and Rails"

Cool.
?– Caution Acts_as_tree relies heavily on a has_parent? method that, as expected, returns true when
the foreign key field properly maps to a record with that primary key value. This means that you cannot
assign a valid value to the foreign key field of a top-level record. If you were to set the foreign key value to,
say, the same value as the record??™s primary key, calling a method like ancestors would actually create an
infinite loop!
Step 2: Defining Your acts_as_tree Method
Adding an acts_as_tree method is what really includes all the tree-like functionality in your
model. There are three basic parameters that the method accepts: foreign_key, order, and
counter_cache. All of these parameters are optional. This is the most basic tree you can have:
class Comment < ActiveRecord::Base
acts_as_tree
end
As good as the defaults may be, the options to acts_as_tree are worth explaining.
CHAPTER 5 ?–  BONUS FEATURES 98
foreign_key
By default, the acts_as_tree method assumes that the foreign key column in your table has
a name of parent_id.


Pages:
220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244