---
title: "Agile Web Development with Rails 3nd Edition学习笔记-创建产品目录列表"
author: "tiny.strimp"
date: "2010-04-18T19:48:51Z"
tags: []
categories: ["编程语言"]
slug: "agile-web-development-with-rails-3nd-edition"
draft: false
lastmod: "2010-04-18T19:48:51Z"
id: 646856
url: "https://seaoflinux.iteye.com/blog/646856"
---

按照书上的引导，我们现在该是增加一个新的Controller的时候了。这个Controller用于将产品归类，并产生归类后的产品列表页面。它的名字叫store。
现在我们创建这个Controller：

> ruby script/generate controller store index

执行这个命令之后，我们需要的关于store的文件就都创建好了。
通过观察创建后的文件和内容，我们知道上面命令中最后的那个index是告诉generate生成store的Controller的源码文件时，同时生成一个叫index的方法，以便后面使用。

接下来，我们想要在store/index的页面上显示从所有products中找到的参品列表。首先我们要取得搜索到的产品对象。所以，我们需要在store_controller.rb文件的index方法中添加取得对象列表的代码。

```Ruby
def index
  @products = Product.find_products_for_sale
end
```

从上面的代码可以看到，搜索的工作其实是Product类中的find_products_for_sale方法来完成的。但是我们现在还没有这个方法。那么我们就需要在modules/product.rb文件中添加这个方法。

```Ruby
def self.find_products_for_sale
  find(:all, :order => "title")
end
```

这里，我们定义该方法时，前面添加了“self.”是为了使这个方法成为类方法，而不是一个实例方法。因为我们在调用的时候实际上是通过Product这个类型来调用的。
这个方法中的处理实际上只有一行，使用了Rails的find方法。其中参数“:all”是说明我们需要所有满足条件的记录行。而“:order => “title””则说明我们希望结果按照字母顺序对title进行排序。

数据都拿到了，那么接下来我们该为显示做点工作了。我们将在app/views/store/index.html.erb文件中添加我们的显示代码。具体代码如下：

```Ruby
<h1>Your Pragmatic Catalog</h1>

<% for product in @products -%>
  <div class="entry">
    <%= image_tag(product.image_url)%>
    <h3><%=h product.title%></h3>
    <%= product.description %>
    <div class="price-line">
    <span class="price"><%= product.price %></span>
    </div>
  </div>
<% end %>
```

（注：<%=h ... %>中的h()方法可以将中间的字符串中所有的html标记都清除掉。从安全的角度来讲，这将会是很好的。仅当你能够确定你的字符串是安全的时候，将h去掉才是对的。）

现在，我们启动我们的网站服务，在浏览器的地址栏中输入“http://localhost:3000/store”，就可以看到产品的catelog列表的实际样子了。
下图就是实际的显示效果图。不管怎么说，看起来还不错。 :D
![](http://dl.iteye.com/upload/attachment/236335/9df7df99-deeb-3500-abd1-0f4e34fc7eb4.jpg)