我正在使用acts_as_api
为我系统中的某些模型提供JSON响应。我的API相关代码(减少以使示例更容易):
# File app/modes/item.rb
# API
acts_as_api
api_accessible :v1_list do |template|
template.add :id
template.add :client_name
end
此API按预期工作。重要的是要知道client_name
是一个包含以下内容的方法:
def client_name
client.name
end
也就是说,客户端名称不包含在项目模型中,而是包含在客户端模型中。因此,此信息不包含在items表中。
使用Bullet gem我注意到在clients表中正在执行N + 1查询。对于每个项目,还会执行对clients表的SQL查询。
我知道ActiveRecord在API中有一些避免N + 1查询的实用程序,我想知道是否有办法将ActiveRecord功能与acts_as_api
gem一起使用。
答案 0 :(得分:2)
宝石documentation显示了这个
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