Ruby on rails 为什么Mongoid::Criteria可以使用对象';那是什么?
我是RoR新手,在使用Mongoid时面临问题。Ruby on rails 为什么Mongoid::Criteria可以使用对象';那是什么?,ruby-on-rails,mongoid,Ruby On Rails,Mongoid,我是RoR新手,在使用Mongoid时面临问题。 代码是由其他人编写的,但我需要做一些修改。 以下是模型中的代码: class AClass include Mongoid::Document field :data, type: String ... scope ... def self.search(params) AClass.only(...)# return a Criteria Object end def as_json(o
代码是由其他人编写的,但我需要做一些修改。
以下是模型中的代码:
class AClass
include Mongoid::Document
field :data, type: String
...
scope ...
def self.search(params)
AClass.only(...)# return a Criteria Object
end
def as_json(options={})
...
end
end
以及控制器中的代码:
def index
@res = AClass.search(query_params) # @res is a Criteria Object
respond_to do |format|
format.json { render json: @res.as_json(format: params[:format],
path: request.env['ORIGINAL_FULLPATH']) } # why AClass's as_json is called
format.xml { render xml: @res.as_json(format: params[:format],
path: request.env['ORIGINAL_FULLPATH']).
to_xml(root: "root",
camelize: true) }
format.html
end
end
我有两个问题:
只有方法属于Mongoid::Criteria
并且Mongoid::Document
模块不包含Criteria
类。上述代码中仅包含Mongoid::Document
。为什么在self.search
中只能调用
Mongoid::Criteria
。但是,当我请求json数据时,@res.as_json
可以调用AClass
的as_json
方法。为什么?Mongoid::Criteria
,并且Mongoid::Document
模块不包含Criteria
类。只有
Mongoid::Document
包含在上述代码中。为什么唯一的答案是
在self.search中调用
只能找到委托给via的方法(请随意翻阅代码)
我发现only
的返回值是Mongoid::Criteria
。但是,当我请求json数据时,@res.as_json
可以调用
AClass
的作为json
方法。为什么?
Mongoid::Criteria#as_json
对基础文档集合调用as_json
,该集合对每个基础文档调用as_json
:
:
# Needed to properly get a criteria back as json
#
# @example Get the criteria as json.
# Person.where(:title => "Sir").as_json
#
# @param [ Hash ] options Options to pass through to the serializer.
#
# @return [ String ] The JSON string.
def as_json(options = nil)
entries.as_json(options)
end