简体   繁体   中英

Why Mongoid::Criteria could use the object's as_json?

I am new to RoR and facing problem using Mongoid.
The code was written by someone else, but I need to do some modifications.
Here's the code in model:

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

And the code in controller:

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

I have two questions:

  1. I found only method belongs to Mongoid::Criteria and Mongoid::Document module does not contain the Criteria Class. Only Mongoid::Document is included in the code above. Why the only could be called in self.search ?

  2. I found that the returned value of Only is Mongoid::Criteria . However, when I request json data, the @res.as_json could call the AClass 's as_json method. Why?

  1. I found only method belongs to Mongoid::Criteria and Mongoid::Document module does not contain the Criteria Class. Only Mongoid::Document is included in the code above. Why the only could be called in self.search ?

The only method can be found in Mongoid::Criteria::Queryable::Optional which is delegated to via Mongoid::Document (feel free to dig around the code).

  1. I found that the returned value of only is Mongoid::Criteria . However, when I request json data, the @res.as_json could call the AClass 's as_json method. Why?

Mongoid::Criteria#as_json calls as_json on the underlying documents collection which calls as_json on each underlying document:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM