再一次从 Postgresql 转到 Mongodb 了,最主要的原因还是以下两点:
Mongodb 是 Schema Less 的,无需再维护一个 schema 文件和 migrate 目录了Mongoid 是数据库定义和操作都放在一块的,而 ActiveRecord
数据库定义和操作是分离的。
换成 Mongodb 之后需要两个地方需要修改。
第一个就是 has_secure_password
使用时,需要在文件首部添加 include ActiveRecor::SecurePassword
第二个就是本文说到的 Friendly mongoid_slug
的 Gem,使用了一会,发现有点别扭,因为它定义了一个 slug
方法覆盖了我数据库中的一个属性,导致原来的 slug
属性无法操作了。想了一会决定自己实现一个简单的方法。
module Mongoid module FriendlyId extend ActiveSupport::Concern included do cattr_accessor :friendly_field end module ClassMethods def friendly_with(field) if self.fields.keys.include?(field.to_s) self.friendly_field = field.to_sym else raise end end def friendly_find(value) find_by(friendly_field => value) end end endend
使用时,只需包含这个 Mongoid::FriendlyId
这个模块,然后用 friendly_with
选择一个期望的列,然后 controller 里把 find
改为 friendly_find
就行了。
class Post include Mongoid::Document include Mongoid::FriendlyId field :slug friendly_with :slugend
Post.friendly_find(params[:id])
本文出自:http://blog.sloger.info/, 原文地址:http://sloger.info/posts/rails-friendly-id-with-mongoid, 感谢原作者分享。 相信成功的信念比成功本身更重要,