创建商店控制器
rails generate controller store index
修改../config/routes.rb 使http://localhost:3000/store/index 成为根目录
加 root 'store#index'
Rails.application.routes.draw do
get 'store/index'
resources :products
root 'store#index'
end
假定可以从模型中得到可销售的商品清单
修改 /app/controllers/store_controller.rb
class StoreController < ApplicationController
def index
@products = Product.all
end
end
修改 /app/models/product.rb 以字母顺序显示商品清单
添加default_scope {order(:title)}
编写视图模板/app/views/store/index.html.erb
<% if notice %>
<p id="notice"><%= notice %></p>
<% end %>
<h1>Your Pragmatic Catalog</h1>
<% @products.each do |product| %>
<div class="entry">
<%= image_tag(product.image_url) %>
<h3><%= product.title %></h3>
<%= sanitize(product.description) %>
<div class="price_line">
<span class="price"><%= product.price %></span>
</div>
</div>
<% end %>
在没有其他页面布局的情况下,所有控制器的视图会用/app/views/layouts/application.html.erb 这个布局
现在设置一个占位布局
<!DOCTYPE html>
<html>
<head>
<title>Pragprog Books Online Store</title>
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %>
<%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
<%= csrf_meta_tags %>
</head>
<body id='store'>
<div id='banner'>
<%= image_tag('logo.png') %>
<%= @page_title || "Pragmatic Bookshelf" %>
</div>
<div id='columns'>
<div id='side'>
<a href="http://localhost:3000/">home</a> <br/>
<a href="#">Questions</a><br/>
<a href="#">News</a><br/>
<a href="#">Contact</a><br/>
</div>
<div id='main'>
<%= yield %>
</div>
</div>
</body>
</html>
在depot.css 中加入以下代码
#banner {
background: #9c9;
padding-top: 10px;
padding-bottom: 10px;
border-bottom: 2px solid;
font: small-caps 40px/40px "Times New Roman", serif;
color: #282;
text-align:center;
}
#banner img{
float: left;
}
#columns {
background: #141;
}
#main {
margin-left: 17em;
padding-top: 4ex;
padding-left: 2em;
background: white;
}
#side{
float: left;
padding-top: 1em;
padding-left: 1em;
padding-bottom: 1em;
width: 16em;
background: #141;
}
#side a{
color: #bfb;
font-size: small;
}
修改/app/views/store/index.html.erb 设置国际化价格格式化
<span class="price"><%= product.price %></span> 改为
<span class="price"><%= number_to_currency(product.price) %></span>