Delving Deeper into the Active Record with Ruby-on-Rails - Mapping and Rails in the Real World (Page 4 of 4 )
Now let's look how the mapping discussed fits into the whole Rails framework. I will be extending the existing application developed in the previous part by adding a new table and corresponding operations. I will provide a custom view part to show the use of the tree data structure. So let's get started. First comes the table. It's the CATEGORIES table, and here is the DDL for it:
Next comes the model corresponding to the table. The command to generate the model class is:
ruby script/generate model User
In the generated class I am giving the declaration acts_as_tree to tell the framework that I need the tree data structure.
class Category < ActiveRecord::Base
acts_as_tree :order => "name"
As you can see, I am reusing the table and model discussed in the previous section.
Next comes the controller. The command to create the controller is:
ruby scriptgenerate controller Mapping
class MappingController < ApplicationController
Every other operation will be provided with a default scaffold except for listing/view. Next comes the definition of listing. Since the application is for a tree structure, the operation for creating the tree will be done in the list method.
Next is the list.rhtml. Here is the code for list.rhtml.
<% subcat=@root. root.children.first%>
<!-same for all others
That brings us to the end of this part. However, the services provided by Active Record are many. The most important are data validation, transactions and single table inheritance. These will be topics of discussion in the future. Till then...
DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.