rails new depot
cd depot
生成脚手架
rails generate scaffold Product title:string description:text image_url:string price:decimal
在 ../depot/db/migrate/ 中会生成迁移文件 20150912100114_create_products.rb
修改些文件,指定价格属性 8位有效数字,小数点后两位
t.decimal :price, precision => 8, :scale =>2
让rake 将所有尚未执行的迁移应用到数据库中
rake db:migrate
可以通过 rake test 测试程序是否有错
此时可通过rake s运行程序 http://localhost:3000/products 中添加商品
也可通过 rails导入数据
修改 /depot/db/ 目录中的seeds.rb的文件
为:
Product.delete_all
Product.create(:title=> 'Programming Ruby 1.9',
:description =>
%{<p>
one and one
</p>},
:image_url => 'http://pic.nipic.com/2007-11-09/2007119122519868_2.jpg',
:price =>49.50)
这会删除已有的数据
rake db:seed 执行
可从http://media.pragprog.com/titles/rails4/code/rails30/depot_b/db/seeds.rb
http://media.pragprog.com/titles/rails4/code/rails30/depot_b/public/images/
http://media.pragprog.com/titles/rails4/code/rails30/depot_b/public/stylesheets/depot.css
下载对应文件
放在/public/images/ /public/stylesheets/ 覆盖/db/seeds.rb
/depot/app/assets/ 下也有
images stylesheets 不行的话,可以试试放在这位置
编辑/app/views/products/index.html.erb
为:
<div id="product_list">
<h1>Listing Products</h1>
<table>
<% @products.each do |product| %>
<tr class="<%= cycle('list_line_odd','list_line_even') %>">
<td>
<%= image_tag(product.image_url, :class => 'list_image') %>
</td>
<td calss="list_description">
<dl>
<dt><%= product.title %></dt>
<dd><%= truncate(strip_tags(product.description),
:lenth => 80) %></dd>
</dl>
</td>
<td calss="list_actions">
<%= link_to 'Show', product %><br/>
<%= link_to 'Edit', edit_product_path(product) %><br/>
<%= link_to 'Destroy', product,
:confirm => 'Are you sure?',
:method => :delete %>
</td>
</tr>
<% end %>
</table>
</div>
<br>
<%= link_to 'New Product', new_product_path %>
rails s 运行 http://localhost:3000/products