如何在active_admin中包含关联的模型

时间:2014-01-28 23:08:21

标签: ruby-on-rails activeadmin eager-loading

在Rails应用程序中,我有两个这样的模型:

class Painting < ActiveRecord::Base
  belongs_to :artist
end

class Artist < ActiveRecord::Base
  belongs_to :country

  def display_name
    text = to_s
    if birth_year
      death = death_year || "----"
      text += " (#{birth_year}-#{death})"
    end
    text += ", #{country.name}"
  end

end

class Country < ActiveRecord::Base
  active_admin_translates :name
end

我使用像这样的活跃管理员

ActiveAdmin.register Painting do
end

问题不是display_name方法需要调用国家/地区和翻译表。有很多艺术家,而且运行起来很长。我正在寻找一种提高速度的方法。

请求似乎是这样的:

SELECT "artists".* FROM "artists" WHERE "artists"."accepted" = 't' ORDER BY name
SELECT "countries".* FROM "countries" WHERE "countries"."id" = 50 ORDER BY name LIMIT 1

要求所有艺术家进行此输入: select image

我该怎么办?

1 个答案:

答案 0 :(得分:1)

您是否尝试在控制器上设置scoped_collection?

我认为是这样的:

ActiveAdmin.register Painting do
  controller do
    def scoped_collection
      Painting.joins({artist: {country: :translations}})
    end
  end
end

此处提供了更多信息:http://www.activeadmin.info/docs/2-resource-customization.html