Mysql 充当api和bullet N+;1查询
我正在使用Mysql 充当api和bullet N+;1查询,mysql,ruby-on-rails,ruby,activerecord,rails-bullet,Mysql,Ruby On Rails,Ruby,Activerecord,Rails Bullet,我正在使用acts\u as\u api为系统中的一些模型提供JSON响应。我的API相关代码如下(为了使示例更简单,减少了代码): 此API正在按预期工作。重要的是要知道,client\u name是一种包含以下内容的方法: def client_name client.name end 也就是说,客户机名称不包含在项目模型中,而是包含在客户机模型中。因此,items表中不包含此信息 使用gem,我注意到正在clients表中执行N+1查询。对于每个项目,还将执行对clients表的
acts\u as\u api
为系统中的一些模型提供JSON响应。我的API相关代码如下(为了使示例更简单,减少了代码):
此API正在按预期工作。重要的是要知道,client\u name
是一种包含以下内容的方法:
def client_name
client.name
end
也就是说,客户机名称不包含在项目模型中,而是包含在客户机模型中。因此,items表中不包含此信息
使用gem,我注意到正在clients表中执行N+1查询。对于每个项目,还将执行对clients表的SQL查询
我知道ActiveRecord在API中有一些避免N+1查询的实用程序,我想知道是否有一种方法可以将ActiveRecord功能与acts as\u API
gem一起使用。gem显示了这一点
def index
@users = User.all
#Note that it’s wise to add a root param when rendering lists.
respond_to do |format|
format.xml { render_for_api :name_only, :xml => @users, :root => :users }
format.json { render_for_api :name_only, :json => @users, :root => :users }
end
end
因此,对于您的情况,您只需加载客户机关联即可
def index
@items = Item.includes(:client).all
# Note that it’s wise to add a root param when rendering lists.
respond_to do |format|
format.xml { render_for_api :name_only, :xml => @items, :root => :items }
format.json { render_for_api :name_only, :json => @items, :root => :items }
end
end
宝石显示了这一点
def index
@users = User.all
#Note that it’s wise to add a root param when rendering lists.
respond_to do |format|
format.xml { render_for_api :name_only, :xml => @users, :root => :users }
format.json { render_for_api :name_only, :json => @users, :root => :users }
end
end
因此,对于您的情况,您只需加载客户机关联即可
def index
@items = Item.includes(:client).all
# Note that it’s wise to add a root param when rendering lists.
respond_to do |format|
format.xml { render_for_api :name_only, :xml => @items, :root => :items }
format.json { render_for_api :name_only, :json => @items, :root => :items }
end
end
这是正确的!acts_as_api不会干扰AR预加载的最佳实践,如包括/预加载。如果您正确预加载AR关联,则不会导致其他查询。这是正确的!acts_as_api不会干扰AR预加载的最佳实践,如包括/预加载。如果正确预加载AR关联,则不会导致其他查询。