In this second part of a three-part series on building an online book catalog in Ruby-on-Rails, you'll learn how to set up the application to allow users to view book details and search for books. This article is excerpted from chapter four of the book Practical Rails Projects, written by Eldon Alameda (Apress; ISBN: 1590597818).
Browsing and Searching an Online Book Catalog (Page 1 of 4 )
Implementing the View Book Details User Story
Having a catalog page for a series of books is nice, but it’s not suitable for excruciating details about every item. Therefore, the next thing for us to do is to implement a page for individual titles. As always, we start by writing a test for this story.
We already have a test case, so we can just extend that. Intest/integration/ browsing_and_searching_test.rb, we’ll add another chapter to the story of Jill, right belowtest_browsing_the_site:
def test_getting_details jill = enter_site(:jill) jill.get_book_details_for "Pride and Prejudice" end
Then we add a new method to ourBrowsingTestDSL module to keep the test code clean:
Theget_book_details_formethod simply fetches a book with the given name from the database, then requests the correspondingshowpage and checks that both the book title and the names of the authors are correctly displayed on the resulting page.
When we createdCatalogController, we specified that we want to have an action calledshowat hand. Therefore, we already have a stub methodshowinapp/controllers/catalog_controller.rband a pretty much empty view fileapp/views/catalog/show.rhtml. Let’s now add some flesh around these bones.
Modifying the Controller
Implementing theshow action inCatalogControlleris a simple two-liner. Add the following toapp/controllers/catalog_controller.rb:
All we do is to assign the@bookinstance variable with the book that matches theidwe get from the browser. If the book is not found, we show a very simple 404 Not Found page. Then we put the title of the book in the@page_titleinstance variable to make it show in the layout.
Modifying the View
In the view file, we’ll show the details of the book at hand (remember that the book title is shown by the layout file inside anh1element). Add the following toapp/views/catalog/show.rhtml:
<p><%= link_to "Back to Catalog", :action => "index" %></p>
Now the view will show the names of all the authors of a book separated by a comma. We also show the cover image of the book if one has been added, and other details of the book. We run the test again, and see that everything works just fine.