ActiveAdmin: Sort by association (belongs_to)

自作多情 提交于 2019-12-24 20:37:51

问题


I have an index admin view where I'm displaying an associated model City. I'd like to be able to sort by city name, but when I click the column header to sort I get the following error:

ActiveRecord::StatementInvalid in Admin/deals#index

SQLite3::SQLException: no such column: cities.name: SELECT  "deals".* FROM "deals"  ORDER BY cities.name desc LIMIT 30 OFFSET 0

Index view

ActiveAdmin.register Deal do
  index do
     column :id
     column :city
  end
  ...
end

Model

class Deal < ActiveRecord::Base
  belongs_to :city
end

How can I sort by city?


回答1:


With Rails 3 or 4:

index do
  column :city, :sortable=>:"cities.name"

  ...
end

And then, in the same file, you need this so that the Deal queries include the City attributes:

controller do
  def scoped_collection
    Deal.includes(:city)
  end

  ...
end



回答2:


Take a look at https://github.com/gregbell/active_admin/pull/623#issuecomment-2419393 and the following comments. You have to tell activeadmin how to do the sorting - probably something like column :city, :sortable => 'cities.name' and define a joined scope before you define the deals index page. Something like

scope :joined, :default => true do |deals|
  deals.includes [:city]
end


来源:https://stackoverflow.com/questions/11266498/activeadmin-sort-by-association-belongs-to

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!