进入Ruby on Rails世界
http://tech.ddvip.com 2008年01月18日 社区交流
内容摘要:Rails是使用纯ruby编写的框架(framework)。它对web开发提供了强有力的支持,如支持数据映射、MVC模式、Web Services、安全等。而且这些功能操作起来要比同类的产品容易的多,如MVC模式就比struts更容易使用。
第一步 初始化
rails diary
cd diary
第二步 建立数据库
create database diary;
create table records (
`id` int(10) unsigned NOT NULL auto_increment,
`title` varchar(50) NOT NULL,
`content` mediumtext NOT NULL,
`date` char(10) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `Index_2` (`date`)
) ENGINE=InnoDB DEFAULT CHARSET=gb2312;
第三步 编写数据表映射类
在appmodels中建立record.rb文件,在其中输入如下代码:
class Record < ActiveRecord::Base
establish_connection(
:adapter => "mysql",
:host => "localhost",
:username => "root",
:encoding => "gb2312",
:password => "password",
:database => "diary"
)
end
注: :encoding => "gb2312" 是必须的,如果没有,汉字就无法保存在数据库中了。
第四步 编写控制类
在appcontrollers中建立diary_controller.rb文件,在其中输入如下代码。
class DiaryController < ApplicationController
before_filter :configure_charsets
def configure_charsets
@response.headers["Content-Type"] = "text/html; charset=gb2312"
end
def index
end
def write
# 查找当天的记录,看看今天是否已经有日记了
@record = Record.find_by_date(Time.now.strftime("%Y-%m-%d"))
if @record == nil # 如果没有,增加一条记录
@record = Record.new
end
end
def create
@record = Record.find_by_date(Time.now.strftime("%Y-%m-%d"))
if @record == nil
@record = Record.new
@record.date = Time.now.strftime("%Y-%m-%d")
end
# 保存数据
if @record.update_attributes(params[:record])
@saved = true
else
@saved = false
end
end
def query
end
def result
# 得到提供的日期
@year =@request.params["record[date(1i)]"].to_s;
@month = sprintf("%02d", @request.params["record[date(2i)]"].to_s)
@day = sprintf("%02d", @request.params["record[date(3i)]"].to_s)
@query_date = @year + "-" + @month + "-" + @day
@record = Record.find_by_date(@query_date)
end
end
来源:天极 作者:李宁 责编:豆豆技术应用