Date: 2013-04-09
Title: DataMapper
Tags: ruby,datamapper
学习sinatra的时候,自然会到选择ORM(Object Relational Mapper)的这一步。
ruby的ORM还是蛮多的,比较流行的有rails的ActiveRecord,DataMapper,Sequel。
为什么选择DataMapper呢?我的原因很简单,Sinatra和DataMapper一起出现的次数比较多。那种性能,效率什么的东西对我一个业余选手来说太高深了。
安装很简单
gem intall data_mapper
然后根据数据库选择adapter
gem install dm-sqlite-adapter
rubygem的使用方法都差不多,直接文件中调用就ok了
require 'rubygems'
require 'data_mapper'
数据库连接
DataMapper.setup(:default,"sqlite://#{Dir.pwd}/test.db)
Mysql和Postgres就要求用户名和密码了
DataMapper.setup(:default,'mysql://user:password@hostname/database')
然后定义自己的model
class Post
include DataMapper::Resource
property :id, Serial
property :title, String
property :body, Text
property :create_at, DataTime
end
更多参数参考Properties文档和dm-types文档
Associations
一对多
class Post
has n,:comments
end
class Comment
belongs_to :post
end
多对多
class Categorization
include DataMapper::Resource
property :id, Serial
property :created_at, DateTime
belongs_to :category
belongs_to :post
end
class Post
has n, :categorizations
has n, :categories, :through => :categorizations
end
class Category
has n, :categorizations
has n, :posts, :through => :categorizations
end
最后在model文件添加
DataMapper.finalize
生成表
一种做法是直接在model文件中加入
DataMapper.auto_migrate!
然后把文件运行下就ok啦。
还有一种是在irb中调用model,然后
irb> modelclass.auto_migrate #模型类
现在可以建立对象了
@post= Post.create(
title:"Title",
body:"Body",
created_at:Time.now
)
CRUD
Create
post=Post.new
post.save
Post.create
Read
Post.all
Post.get(1)
Post.first
Post.last
Post.first(title:"Title")
Update
post=Post.first
post.update(title:"New title")
Delete
Post.first.destroy