刚开始用 Mongoid 的时候就发现它不支持 ActiveRecord 里的 find_by_xxx 方法,忍了好久,终于忍无可忍,在 Github 找到一段代码,稍微改写了一下,把这个问题解决了。把这个文件存进 config/initializers/ 里就可以用了。
https://gist.github.com/1381824
module Mongoid
module Finders
# add find_by_xxx to Mongoid
# from https://github.com/mitijain123/mongoid/commit/b28b360b787ba4cd32e5423afcfa3b83574f9df1
def method_missing(method_id, *args, &block)
conditions = {}
bang = false
case method_id.to_s
when /^find_(all|last||first)_?by_([_a-zA-Z]\w*)(!?)$/
finder_type = $1.blank? ? :first : $1.to_sym
bang = true if $3 == '!'
$2.split(/_and_/).each_with_index do |attr, i|
conditions[attr] = args[i]
end
result = find(finder_type, :conditions => conditions)
if result.nil? and bang
raise Mongoid::Errors::DocumentNotFound.new(self.class, args)
else
return result
end
else
nil
end
end
end
end