学习ROR(3)
接着上次,我们先打开xxxxxx_create_products.rb
class CreateProducts < ActiveRecord::Migration def change create_table :products do |t| t.string :title t.string :description t.string :image_url t.decimal :price t.timestamps end end end
这个类是我们用scaffold生成的,CreateProducts类就是用来生成数据库中对应的Products表。这个类继承至rails的ActiveRecord:Migration,它提供了很多操作。例如这里的create_table
函数,它用来创建:products表,并且表的四个列分别是title,description,image_url,price和timestamps.注意到前4个是我们在scaffold时设置的,timestamps时rails自动给每个表添加的
时间戳。更多关于Migration的内容可以查看这里。
接下来我们先做些修改,把价格设定为8位有效位数以及2位的小数。
class CreateProducts < ActiveRecord::Migration def change create_table :products do |t| t.string :title t.string :description t.string :image_url t.decimal :price, :precision => 8, :scale => 2 t.timestamps end end end
现在我们把改动提交的数据库中
workpath> rake db:migration
在数据库中查看下
mysql> show columns from products; +-------------+--------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------------+--------------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | title | varchar(255) | YES | | NULL | | | description | varchar(255) | YES | | NULL | | | image_url | varchar(255) | YES | | NULL | | | price | decimal(8,2) | YES | | NULL | | | created_at | datetime | NO | | NULL | | | updated_at | datetime | NO | | NULL | | +-------------+--------------+------+-----+---------+----------------+ 7 rows in set (0.01 sec)
db:migration会扫描整个还没有被更新的文件来更新数据库,做迭代的添加。
然后我们就可以先试着看看我们的网站了。首先我们启动本地服务,端口3000
workpath> rails s
(s 是server的意思,另有一些参数可用,如-debug)
在浏览器中观看一下,如果能看到下面的界面就说明rails的服务启动成功了
然后看看我们的products界面(这个界面是rails的scaffold自动生成的)
尝试下创建一个新的product,点击‘New Product’
点击创建,我们可以看到如下界面
以上所有的界面和操作都有scaffold自动生成好了,非常的方便。但是很丑,并且我们要做我们自己的业务逻辑,所以接下来我们要对它进行改造了。

浙公网安备 33010602011771号