例如,我有两个文件
class Task
include Mongoid::Document
field :name, type: String
belongs_to :person
end
和
class Person
include Mongoid::Document
field :name, type: String
has_one :stage
end
我的控制器中有一个方法
def index
tasks = Task.all
render :json => tasks.to_json(:include => :person)
end
查看生成的查询,我看到它查找每个任务的人(当前有3个任务)
MOPED: 127.0.0.1:27017 QUERY database=pipeline_development collection=tasks selector={} flags=[:slave_ok] limit=0 skip=0 fields=nil (0.3619ms)
MOPED: 127.0.0.1:27017 QUERY database=pipeline_development collection=people selector={"$query"=>{"_id"=>"50f12eb2cce8b43b05000001"}, "$orderby"=>{:_id=>1}} flags=[:slave_ok] limit=-1 skip=0 fields=nil (0.1998ms)
MOPED: 127.0.0.1:27017 QUERY database=pipeline_development collection=people selector={"$query"=>{"_id"=>"50f12eb2cce8b43b05000001"}, "$orderby"=>{:_id=>1}} flags=[:slave_ok] limit=-1 skip=0 fields=nil (0.3881ms)
MOPED: 127.0.0.1:27017 QUERY database=pipeline_development collection=people selector={"$query"=>{"_id"=>"50f12eb2cce8b43b05000001"}, "$orderby"=>{:_id=>1}} flags=[:slave_ok] limit=-1 skip=0 fields=nil (0.2272ms)
这实际上可以加起来(我的数据库中每次查找的时间实际上是25ms而不是0.3ms)并导致不合理的缓慢。
有关如何解决此问题的任何建议吗?
修改
我试着加载
def index
tasks = Task.all.includes(:person)
render :json => tasks.to_json(:include => :person)
end
但它似乎没有改变任何东西