一直在研究Ruby-China的源代码,RC中使用的是Mongodb. 我也准备尝试一下mongodb。
- 新建项目
rails new mongodb --skip-active-record
生成一个叫mongodb的项目,并且移除active-record的代码
- 引入Gem
修改Gemfile文件
gem 'mongoid', '3.0.0.rc'
运行:
bundle install
- 生成配置文件
rails g mongoid:config
使用默认的吧
- 生成代码
rails g scaffold blog title:string content:text
- 启动程序
rails s
- 访问
http://127.0.0.1:3000/blogs
- 看看我们的一个新的需求吧,我们需要假(软)删除 blog,该怎么办呢?其中一个办法就是设置一个 deleted_at 字段,假删除。
但是 软删除是一个公共的需求,看看RubyChina是如何做的吧。
在model/mongoid/soft_delete.rb代码如下
# coding: utf-8
# 软删除
module Mongoid
module SoftDelete
extend ActiveSupport::Concern
included do
field :deleted_at, :type => DateTime
default_scope where(:deleted_at => nil)
alias_method :destroy!, :destroy
end
def destroy
if persisted?
self.update_attribute(:deleted_at,Time.now.utc)
end
@destroyed = true
freeze
end
end
end
代码解说:
ActiveSupport::Concern http://blog.csdn.net/hexudong08/article/details/7656396
freeze: 冻结所有的值,以后不能修改了,可以通过 frozen? 判断
将代码放到model中,会自动的加载。在model中可以直接引用
最后的blog代码
class Blog
include Mongoid::Document
include Mongoid::Timestamps #会自动生成created_at和update_at字段
include Mongoid::SoftDelete
field :title
field :content
end
- 如何取出非默认的scoped的数据,也就是删除了的blog呢?RubyChina的做法
@topics = Topic.unscoped.desc(:_id).includes(:user)...