Ruby on Sinatra:使用ActiveRecord连接数据库

Posted by baicai on November 16, 2015

Active Record 是 <a href=”http://guides.ruby-china.org/getting_started.html#the-mvc-architecture”>MVC</a> 中的 M(模型),处理数据和业务逻辑。Active Record 负责创建和使用需要持久存入数据库中的数据。Active Record 实现了 Active Record 模式,是一种对象关系映射系统。

使用方式:

加载ActiveRecord配置

#ActiveRecord::Base.establish_connection(:adapter => "mysql2",
#:host => "localhost", :database => "mysql",
#:username => "root", :password => "root")
dbconfig = YAML.load(File.open('config/database.yml'))['production']&nbsp;
ActiveRecord::Base.establish_connection(dbconfig)

adapter指定了连接时的驱动,如sqlite,mysql等

建立相应的类

class PromoteApp < ActiveRecord::Base
	self.table_name = "promote_app"
	self.primary_key = "_id"
end

建立的类名和数据库名最好符合相应的规范,这样就能自动对应上,否则需要指定table_name,如果主键不是id,还需要手动指定主键。

#数据表名:复数,下划线分隔单词(例如 book_clubs)
#模型类名:单数,每个单词的首字母大写(例如 BookClub)</pre>

增删改查

新增数据

user = User.create(name: "David", occupation: "Code Artist")
#或者
user = User.new
user.name = "David"
user.occupation = "Code Artist"
user.save

查询数据

# return a collection with all users
users = User.all

# return the first user
user = User.first

# return the first user named David
david = User.find_by(name: 'David')

# find all users named David who are Code Artists and sort by created_at
# in reverse chronological order
users = User.where(name: 'David', occupation: 'Code Artist').order('created_at DESC')

#按created_at倒叙排列,从第11个数据开始取5个
users = User.order("created_at DESC").limit(5).offset(10)

修改数据

user = User.find_by(name: 'David')
user.name = 'Dave'
user.save
#或
user = User.find_by(name: 'David')
user.update(name: 'Dave')

删除数据

user = User.find_by(name: 'David')
user.destroy
更多信息:http://guides.ruby-china.org/active_record_basics.html