acts_as_api 和项目符号 N+1 查询

acts_as_api and bullet N+1 queries

我正在使用 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

也就是说,客户端名称不包含在项目模型中,而是包含在客户端模型中。因此,此信息不包含在项目 table 中。

使用 Bullet gem 我注意到客户端 table 正在执行 N+1 查询。对于每个项目,还执行对客户端 table 的 SQL 查询。

我知道 ActiveRecord 在 API 中有一些实用程序可以避免 N+1 查询,我想知道是否有办法将 ActiveRecord 功能与 acts_as_api gem.

gemdocumentation显示了这个

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