按belongs_to关系中的父项订购active_admin列

时间:2015-09-17 18:32:06

标签: ruby-on-rails ruby ruby-on-rails-4 activerecord activeadmin

我有两个模型:show_requestshowshow_Request属于_ showshow has_many show_requests。在active_admin的show_request页面上,我想按show_requests的{​​{1}}值排序show。到目前为止,这是我的代码:

created_at

以下是服务器日志:

ActiveAdmin.register ShowRequest do

  controller do
    def scoped_collection
      end_of_association_chain.includes(:show)
      #I also tried ShowRequest.includes(:show)
    end
  end

  index do
    column 'Show', sortable: "shows.created_at_asc" do |show_req|
        link_to show_req.show.name, admin_show_path(show_req.show)
    end
  end

end

这不起作用。它根本不影响列的顺序。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

看一下日志的这一部分:

ShowRequest Load (2.0ms)  SELECT  "show_requests".* FROM "show_requests"  WHERE (not_going_to_show = 'f' OR i_want_my_horse_to_compete = 't')  ORDER BY "show_requests"."id" desc LIMIT 30 OFFSET 0
Show Load (9.7ms)  SELECT "shows".* FROM "shows"  WHERE "shows"."id" IN (2, 1)

您可以看到ShowRequestShow已加载到单独的查询中。 sortable在这里不起作用,因为你不能在没有连接的情况下通过另一个字段来排序一个表。修复应该告诉ActiveRecord您需要在查询中引用shows表:

controller do
  def scoped_collection
    super.includes(:show).references(:shows)
  end
end

index do
  column :show, sortable: 'shows.created_at'
end

references仅适用于includes,并强制Rails在急切加载时执行连接。