|
我使用 Sqlite 的最主要的原因是它的一个数据库就是一个文件。备份或转移只要按一般文件的方式就可以了。
Sqlite 说到底是一种无类型的数据库。目前它支持5种数据类型。
1. NULL 空。值是 NULL 2. INTEGER 整数。 根据整数的大小自动决定是存1字节,2字节还是更多 3. REAL 实数。 以 8-byte IEEE 浮点数存储 4. TEXT 文本。以 UTF-8, UTF-16BE 或 UTF-16-LE 保存文本 5. BLOB 二进制。存储二进制值
可以看出没有Time,Date 等类型。但在一个Blog的程序中,这可能是必需的。我的解决方法是用Integer 当 Timestamp 用。
Database Schema blog.sql
| 代码: |
-- post create table posts ( id integer not null, poster_id integer, create_time integer, modified_time integer, title text, content text, category_id integer, primary key (id) ) ;
-- poster create table posters ( id integer not null, username text, password text, firstname text, lastname text, email text, website text, primary key (id) ) ;
-- category create table categories ( id integer not null, name text, primary key (id) ) ;
-- comments create table comments ( id integer not null, post_id integer, poster_id integer, create_time integer, content text, primary key (id) ) ; |
建立数据库 cd db sqlite3 blog.db < blog.sql cp blog.db blog_test.db "blog.db" 可以起任意的名字,任意的后缀
更改 config/database.yml
| 代码: |
development: adapter: sqlite3 dbfile: db/blog.db
test: adapter: sqlite3 dbfile: db/blog_test.db
production: adapter: sqlite3 dbfile: db/blog.db
|
时间转换成 Timestamp,本段代码在 controller.rb 中
| 代码: |
def create @post = Post.new(params[:post]) @post.create_time = ::Time.now.to_i if @post.modified_time == nil @post.modified_time = @post.create_time end if @post.save flash[:notice] = 'Post was successfully created.' redirect_to :action => 'list' else render :action => 'new' end end |
这里有一个 Ruby 特有的比较方法:“== nil" 。SQL当中NULL的值是不能这样用的,而是用 "IS NULL"
从Timestamp 转换成Time,在 view.rb 中
| 代码: |
<% for post in @posts %> <h2><%= post.title %> </h2> <% i = post.create_time %> <% j = post.modified_time %> <h4>Create at: <%= ::Time.at(i) %></h4> <h4>Modified at: <%= ::Time.at(j) %></h4> <p><%= post.content %></p> <tr> <td><%= link_to 'Show', :action => 'show', :id => post %></td> <td><%= link_to 'Edit', :action => 'edit', :id => post %></td> <td><%= link_to 'Destroy', {:action => 'destroy', :id => post}, :confirm => 'Are you sure?' %></td> </tr> <% end %> |
Time 对象前面一定要加 ::(阅读次数:)
|