rails学习笔记:维护商品信息任务A

本文详细介绍了如何使用Rails生成产品脚手架,包括创建迁移文件、设置价格属性、应用数据库迁移、导入数据和管理产品列表。通过实践示例,展示了如何在Rails环境中高效地进行数据管理和展示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值