Continuing our discussion of Ruby-on-Rails, this article covers the basic services provided by the ActionView. The ActionView helps you present data to your users. Keep reading to learn some terminology and study an example application.
Understanding Action Views in Ruby-on-Rails - ActionView: Pagination and Layouts (Page 3 of 4 )
In the first section I discussed the theory of pagination. In this section I will be discussing how RoR helps in implementing pagination. RoR implements pagination at both the controller and view levels. At the controller level, RoRís pagination controls which rows are retrieved from the database. At the view level it displays the links required for navigation between the pages created by the decomposition of the table. For example, to paginate a list of users, the following steps are taken:
At the Controller:
In the controller, a paginator has to be declared in this way:
def user_list @user_pages, @users = paginate(:users, :order_by => 'name') end
The paginator is set up using the paginate method. The parameters are the table to paginate and the field on which sorting has to be done. It returns two objects, a paginator object which in this case is @user_pages, and an object that contains a page full of users which in this case is @users. The @users is used by the view to display the pages of users. The paginator object fetches the rows from the table and populates the @users variable with the fetched rows.
At the View:
In the corresponding RHTML template, the object containing a list of users is iterated over and displayed. The pagination_links() method is used to set up the page navigation. In code it would be as follows:
<table> <tr><th>Name</th></tr> <% for user in @users %> <tr><td><%= user.name %></td> <% end %> </table> <hr> <%= pagination_links(@user_pages) %> <hr>
Layouts honor the DRY philosophy of RoR. RoR uses the layout to provide templates within templates. In simple terms, it means RoR can render pages that are nested within other rendered pages or templates. This style provides for a typical site wide frame where the site has been divided into four or five different compartments such as banner, menu, footer and so on. A simple layout would look like this:
Here the code is for a standard HTML layout. The thing to look for is the variable @content_for_layout. It contains the content generated by the normal rendering of an action. So if the action (i.e. controller) was:
defmy_action @msg ="Hello, World!" end
and the my_action.rhtml has the following code:
<h1><%= @msg %></h1>
Then the variable @content_for_layout would contain :
Thatís just a glimpse of the power of layout. If you remember the scaffold generated in the first part, it uses layouts to produce the output. The advanced features of layouts will be discussed in the future. The next section will look at a simple application that uses the template and formatting techniques.