开始在MySQL中创建数据库,分别用于:开发、测试、产品
create database chensite_development;
create database chensite_test;
create database chensite_production;
在开发库中建表和插入数据:
use chensite_development;
drop table if exists titles;
create table titles (
id int not null auto_increment,
name varchar(100) not null,
url varchar(200) default NULL,
parent_id int default 0,
expanded tinyint(1) default 0,
level tinyint(1) default 0,
primary key (id)
)ENGINE=InnoDB DEFAULT CHARSET=utf8;
LOCK TABLES titles WRITE;
INSERT INTO titles VALUES(1,'AAAAAAAAA','http:\\www.AAAAAAAAA.com.cn',0,0,1);
INSERT INTO titles VALUES(2,'BBBBBBBBB','http:\\www.BBBBBBBBB.com.cn',0,0,1);
INSERT INTO titles VALUES(3,'CCCCCCCCC','http:\\www.CCCCCCCCC.com.cn',0,0,1);
INSERT INTO titles VALUES(4,'关于','http:\\www.DDDDDDDDD.com.cn',0,0,1);
INSERT INTO titles VALUES(5,'EEEEEEEEE','http:\\www.EEEEEEEEE.com.cn',2,0,2);
INSERT INTO titles VALUES(6,'FFFFFFFFF','http:\\www.FFFFFFFFF.com.cn',2,0,2);
INSERT INTO titles VALUES(7,'GGGGGGGGG','http:\\www.GGGGGGGGG.com.cn',2,0,2);
INSERT INTO titles VALUES(8,'HHHHHHHHH','http:\\www.HHHHHHHHH.com.cn',2,0,2);
UNLOCK TABLES;
配置数据库连接: config\database.yml,主要是给连接三个数据库的root用户输入密码,在输入密码时要注意
:"password:"和密码"123456"之间要有一个空格,密码之后不要有空格,否则无法启动WEB服务。
# MySQL (default setup). Versions 4.1 and 5.0 are recommended.
#
# Install the MySQL driver:
# gem install mysql
# On MacOS X:
# gem install mysql -- --include=/usr/local/lib
# On Windows:
# gem install mysql
# Choose the win32 build.
# Install MySQL and put its /bin directory on your path.
#
# And be sure to use new-style password hashing:
# http://dev.mysql.com/doc/refman/5.0/en/old-client.html
development:
adapter: mysql
database: chensite_development
username: root
password: 123456
host: localhost
# Warning: The database defined as 'test' will be erased and
# re-generated from your development database when you run 'rake'.
# Do not set this db to the same as development or production.
test:
adapter: mysql
database: chensite_test
username: root
password: 123456
host: localhost
production:
adapter: mysql
database: chensite_production
username: root
password: 123456
host: localhost
接下来创建一个能够显示数据库数据的页面。Rails是MVC模式的编程方式。
首先创建数据模型:app\models\title.rb
class Title < ActiveRecord::Base
end
- 数据库titles(小写复数),文件名title.rb(小写单数),类名Title(大写单数)
- 大写方式--单词第一个字母为大写。小写方式--每个单词用下划线分开。
- 模型类中不必定义属性,它会自动以数据库字段为属性。
- set_table_name "table1" 定义对应的表
- set_primary_key "name" 改默认的ID主键为name,不过以后name字段就用成id,如:o.id="chengang"
创建视图:views\homepage\index.rhtml,显示出title表所有记录的id和name值
<html>
<body>
<h1>ChenGang's Site</h1>
<% for title in @titles %>
<%= title.id %>__<%= title.name %><br/>
<% end %>
</body>
</html>
视图中用到的@titles变量来自于我们自己创建的如下控制器: app\controllers\homepage_controller.rb。Rails中控制器中的变量可以在视图中使用(这是否会产生变量污染的问题呢,还待以后再体验)
class HomepageController < ApplicationController
def index
@titles = Title.find(:all)
end
end
- Homepage和视图的目录名homepage相关
- index方法和视图的文件名index.rhtml相关
- 用index可以省略访问地址中的action(action默认为index action)
最后启动Web服务器后访问:http://localhost:3000/homepage