Ruby on Rails实践(5)--- 连上数据库
创建 mybook 数据库
1:打开 MySQL Control Center , 新建 mybook 数据库.

2:新建数据库表 books
表字段的定义如图所示
id int(11) comment '主键'
title varchar(100)
description text
buydate date

3: 告诉 rails 如何找到数据库信息,打开 D:\railsdoc\mybook\config 目录,编辑 database.yml 配置文件。 ruby 程序喜欢用 yaml 作为配置文件,这种做法就象是 java 程序喜欢用 xml 作配置文件一样,是传统习惯了。
新增内容:
YAML 简介:
很多初次接触 Ruby 的人可能会对它采用 yaml 文件作为配置文件感到奇怪。Yaml 库已经内置在 ruby 发行版本中,做为很 “Ruby way”的方式用在各种读取配置的操作中。希望了解 Yaml 格式的人,可以参看一下 http://www.yaml.org
这里翻译一下该网站对 yaml 的解释:
• YAML适合人们阅读
• YAML适合与脚本语言交流
• YAML 使用宿主语言的内部数据结构
• YAML 拥有一致性的信息模型
• YAML使基于流式数据的处理成为可能
• YAML 富于表达和可扩展
• YAML 容易实现
yaml 做为一个可移植的对象序列化方案,可以在不同的Ruby 进程中将对象以普通文本传递,此外也适合ruby与那些支持 yaml 的语言之间交换数据用。
如何将ruby对象保存到 yaml 文件中.
参考文档:
http://www.ruby-doc.org/core/classes/YAML.html
require ‘yaml’
tree = { :name => ‘ruby’,
:uses => [‘script’,’web’,’testing’,’etc’]
}
File.open(“tree.yaml”,”w”) {|f| YAML.dump(tree,f)}
如何在 ruby 程序中读取 yaml 文件。
require ‘yaml’
tree = YAML.load(File.open(“tree.yaml”)
tree[:uses][1]
输出结果: “web”
yaml 格式的一个大用途就是用在存储配置信息,因为它是纯文本格式的,非常适合阅读,同时又很适合 Ruby 等脚本程序将其读取到对象中。
下面就是个例子:
conf/config.yaml 文件内容如下:
host: 127.0.0.1
prefs:
username: mulder
password: trustno1
filename: xfiles

我们可以在ruby 中这样使用它
require ‘yaml’
config = YAML.load(File.open(“conf/config.yaml”))
config[“host”] -- 输出结果 “127.0.0.1”
config[“prefs”][“password”] -- 输出结果 “trustno1”
由于重新定义了数据库配置,需要重新启动 webrick 服务器才能让 rails 找到数据库配置信息。
Page Author
From Here You Can…
Information
- 338 Views
- 0 Comments
Most Recent Related Content
- Video
- Avatar

- Title
- Ruby Idioms - Session 3
- Description
- Author
- Video
- Avatar

- Title
- Ruby Idioms - Session 1
- Description
- Author
- Video
- Avatar

- Title
- Ruby Basics - Session 2
- Description
- Ruby Basics Screen Cast— Session 2
- Author
- Video
- Avatar

- Title
- Ruby Metaclasses - Session 6
- Description
- Author
- Video
- Avatar

- Title
- Ruby Basics - Session 4
- Description
- Author
- Video
- Avatar

- Title
- Ruby Keyword Arguments
- Description
- Author
- Lesson
- Avatar

- Title
- Ruby Coding Convention
- Body
- RubyCodingConvention File Names Directory and File names and Suffixes ...
- Author
- Lesson
- Avatar

- Title
- How to use Fliqz4R
- Body
- About Fliqz Fliqz is the leader in full-service, plug-an...
- Author
Published In…
© 2008 Valiant, All Rights Reserved.