在上一篇隨筆中,我們給Products的創建頁面添加了輸入驗證,今次的內容非常簡單,來稍稍美化下Products的列表頁面。
1.打開app\views\admin\list.rhtml文件,可以看到下面的代碼
<h1>Listing products</h1>
<table>
<tr>
<% for column in Product.content_columns %>
<th><%= column.human_name %></th>
<% end %>
</tr>
<% for product in @products %>
<tr>
<% for column in Product.content_columns %>
<td><%=h product.send(column.name) %></td>
<% end %>
<td><%= link_to 'Show', :action => 'show', :id => product %></td>
<td><%= link_to 'Edit', :action => 'edit', :id => product %></td>
<td><%= link_to 'Destroy', { :action => 'destroy', :id => product }, :confirm => 'Are you sure?', :method => :post %></td>
</tr>
<% end %>
</table>
<%= link_to 'Previous page', { :page => @product_pages.current.previous } if @product_pages.current.previous %>
<%= link_to 'Next page', { :page => @product_pages.current.next } if @product_pages.current.next %>
<br />
<%= link_to 'New product', :action => 'new' %>
可以看到,list頁面實際上是對Products做循環,然後對每行,每列逐個輸出到一個Table中,而link_to函數,我們在前面的內容中也使用過。
2.修改app\views\admin\list.rhtml的內容,如下:
<h1>Product Listing</h1>
<table cellpadding="5" cellspacing="0">
<%
odd_or_even = 0
for product in @products
odd_or_even = 1 - odd_or_even
%>
<tr valign="top" class="ListLine<%= odd_or_even %>">
<td>
<img width="60" height="70" src="<%= product.image_url %>"/>
</td>
<td width="60%">
<span class="ListTitle"><%= h(product.title) %></span><br />
<%= h(truncate(product.description, 80)) %>
</td>
<td align="right">
<%= product.date_available.strftime("%y-%m-%d") %><br/>
<strong>$<%= sprintf("%0.2f", product.price) %></strong>
</td>
<td class="ListActions">
<%= link_to 'Show', :action => 'show', :id => product %><br/>
<%= link_to 'Edit', :action => 'edit', :id => product %><br/>
<%= link_to 'Destroy', { :action => 'destroy', :id => product },
:confirm => "Are you sure?" %>
</td>
</tr>
<% end %>
</table>
<%= if @product_pages.current.previous
link_to("Previous page", { :page => @product_pages.current.previous })
end
%>
<%= if @product_pages.current.next
link_to("Next page", { :page => @product_pages.current.next })
end
%>
<br />
<%= link_to 'New product', :action => 'new' %>
3.在上面的代碼裡,我們可以看到td class="ListActions"這樣的代碼,下來我們添加這些css樣式的內容:
將下面的內容添加到public\stylesheets\ scaffold.css文件中:
.ListTitle {
color: #244;
font-weight: bold;
font-size: larger;
}
.ListActions {
font-size: x-small;
text-align: right;
padding-left: 1em;
}
.ListLine0 {
background: #e0f8f8;
}
.ListLine1 {
background: #f8b0f8;
}
4.再次運行Products的list頁面,可以看到效果,如圖:

OK,今天的內容很簡單,今後我會盡量多寫些自己的東西,不光是抄書了。