Rails Part 2: Adding a Catalog Display
So - on to Part 2 - and I’ve covered the following ground…
- Created a new controller to handle customer interactions
Using the ruby script/generate command again, but this time adding a controller rather than a scaffold.
- Implemented the default index action.
In the script/generate command, to implement the index action, simple add the word ‘index’ after the controller name (‘store’)
- Added a class method to the Product model to provide a list of items for sale.
Back over in Products.rb, a small method was added (using self.methodname to ensure that it is a class method rather than an instance method) to list out the products.
- Implemented a view (via a .html.erb file) and a layout that contains it
The index.html.erb view was the main way to create specific ‘index’ content, but by creating a store.html.erb file in the app/views/layout folder I managed to create an overall layout for the component that uses the expression <% yield: layout %> to include other pages within this layout.
- Use a helper to format prices the way I want
Nice and easy to implement via <%= number_to_currency() %> - seems to default to US Dollars, so I’m not sure how that would work if you want to work with e.g. GBP….but I guess we’ll see?
- Added a button to each item to allow people to add it to the cart.
A simple modification to the index.html.erb template with a rails helper <%= button_to ‘Add to Cart’ %> making things easy.
- Made a simple modification to a stylesheet.
Using Dreamweaver (to make CSS modifications easy), updates to the provided depot.css allowed me to make a nice clean template, and to orientate the buttons within the main page. CSS - so powerful, but incredibly dull to learn, eh?
Also completed the ‘extra’ exercises - adding time/date to the side bar was straightforward using <%= Time.now %> in the store.html.erb.
Adding a hyperlink to the book’s image was a little bit more tricky and required a deeper look at the link_to syntax:
<%= link_to image_tag(product.image_url), { :action => :add_to_cart, :id => product }, :post => true %> Finally, tinkering around with the number_to_currency() helper method allowed me to add GBP and other currency types to the formatting. Options are available to specify :unit, :separator, and :delimiter .
So - that’s the second part of the tutorial completed. In the next lesson, I’m learning how to create the shopping cart itself! See you then!