一直在研究Ruby-China的源代码,RC中使用的是Mongodb. 我也准备尝试一下mongodb。
- 新建项目
生成一个叫mongodb的项目,并且移除active-record的代码rails new mongodb --skip-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.youkuaiyun.com/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)...
本文介绍了如何在Rails应用中集成MongoDB,并通过一个简单的博客示例展示了软删除功能的实现方式。文中详细记录了从项目搭建到模型定义的全过程。
305

被折叠的 条评论
为什么被折叠?



