0

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

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

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

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

4

1 回答 1

3

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
于 2016-02-11T09:19:58.887 回答