您的位置:首页 > 编程语言 > Ruby

RUBY实践—数据库简单操作

2010-04-29 10:27 281 查看
开发环境:

Ruby:1.9.1

Rails:2.3.5

Rake:0.8.7

Rack:1.0.1

Mysql:5.0.9

Ruby-mysql:mysql-2.8.1-x86-mswin

IDE:RubyMine2.0.1



数据库准备:

database:dbdevelopment

user:crystal

password:crystal



一、创建Ruby项目RorTest



二、修改database.yml

这里只启用development环境数据库,修改配置文件如下:

development:
  adapter: mysql
  encoding: utf8
  reconnect: false
  database: dbdevelopment
  pool: 5
  username: crystal
  password: crystal
  host: localhost




三、运行Scaffold

RorTest->New->Scaffold 运行参数:Product title:string description:string price:integer









成功运行后,将在控制台中输出运行过程中创建的目录及文件(包括Model、Help、View等)



四、反向生成数据库表

在db/migrate下找到类似 create_products.rb文件,右键Run







成功运行后将在对应数据库中生成schema_migrations及products数据表





五、修改routes.rb

在routes.rb中添加映射规则

map.connect '/products',:controller=>"product",:action=>"index"
map.connect ':controller/:action/:id'
map.connect ':controller/:action/:id.:format'




六、启动服务器,运行(http://localhost:3000/products





注:Show、Edit、Destroy、New product功能可以自己测试一下,另外如果在model/product.rb中添加如下代码,可以对product中的字段进行必填验证,有兴趣的朋友可以测试一下



class Product < ActiveRecord::Base
#验证必填项
validates_presence_of:title,:price
end

class Product < ActiveRecord::Base
  #验证必填项,message为显示的内容,也可不填 ,如下
  #validates_presence_of:title,:price
  validates_presence_of:title ,:message=>": Please input title"
  validates_presence_of:price, :message=>": Please input price"
end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: