为什么Mongoid :: Criteria可以使用对象的as_json?

问题描述 投票:0回答:1

我是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(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

我有两个问题:

  1. 我发现only方法属于Mongoid::CriteriaMongoid::Document模块不包含Criteria类。只有Mongoid::Document包含在上面的代码中。为什么only可以在self.search中调用?
  2. 我发现Only的返回值是Mongoid::Criteria。但是,当我请求json数据时,@res.as_json可以调用AClassas_json方法。为什么?
ruby-on-rails mongoid
1个回答
1
投票
  1. 我发现只有方法属于Mongoid::CriteriaMongoid::Document模块不包含Criteria类。只有Mongoid::Document包含在上面的代码中。为什么唯一可以在self.search中调用?

only方法可以在Mongoid::Criteria::Queryable::Optional中找到,它被委托给Mongoid::Document(随意挖掘代码)。

  1. 我发现only的返回值是Mongoid::Criteria。但是,当我请求json数据时,@res.as_json可以调用AClassas_json方法。为什么?

Mongoid::Criteria#as_json在基础文档集合上调用as_json,该集合在每个基础文档上调用as_json

mongoid/criteria.rb

# 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
© www.soinside.com 2019 - 2024. All rights reserved.