In this third part of a four-part article series on building an online bookstore application with Ruby on Rails, you'll learn how to actually create authors in the system, validate data, and more. This article is excerpted from chapter two of the book Practical Rails Projects, written by Eldon Alameda (Apress; ISBN: 1590597818).
Validating Author Data in an Online Bookstore - Listing Authors (Page 4 of 4 )
Now that we are able to create authors, it would be nice to be able to view and list the authors in the system, too. We will next implement the author list page, which we’ll make the indexaction of our controller.
At its simplest, we want our author list to show a table with rows for all authors and a header row. Let’s create a test case for it inauthor_controller_test.rb.
In the test, we first check that theindexaction returns a successful HTTP response. Then we check that there is a table with rows for each author in the database and a header row on the resulting page. We do this by using the:childrenand:countoptions ofassert_tag. We also check that there are table cells holding the names of all authors in the database.
Implementing theindexaction is straightforward. In the controller, we just fetch all the authors from the database and set the page title:
def index @authors = Author.find(:all) @page_title = 'Listing authors' end
In the view file,app/views/admin/author/index.rhtml, we then display the table and, at the bottom of the page, a link to add a new author:
<p><%= link_to 'Add a new author', :action => 'new' %></p>
This time, we use the:collectionoption in therendercall to render the_author.rhtmlpartial template once for each author in@authors. Let’s create the partial template (app/views/ admin/author/_author.rhtml) and make it show a table row for each author.
We can now run the test file again and see that everything seems to be in order. Now we will move on to the next user story, viewing the details of an individual author.
Please check back tomorrow for the conclusion to this series.
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.