ActiveAdmin how to sort column with associations

Slicekick picture Slicekick · Jun 22, 2012 · Viewed 16.7k times · Source

I'm developing an ActiveAdmin app, and I want to sort a column of businesses by their "type". Unfortunately my code is not working. What code should I use to accomplish this? Here is my code...

app/models/business.rb


class Business < ActiveRecord::Base   
     belongs_to :type

     attr_accessible :description, :email, :facebook, :foursquare, :google, :manager,
    :mobile, :name, :phone, :type_id, :url, :yelp 
end

app/models/type.rb


class Type < ActiveRecord::Base
  attr_accessible  :category
  has_many :businesses

  def to_s
    category
  end
end

app/admin/businesses.rb


ActiveAdmin.register Business, { :sort_order => :name_asc } do
  scope :joined, :default => true do |businesses|
    businesses.includes [:type]
  end
  index do
    column :name
    column :type, :sortable => 'businesses.type'
    column :manager
    column :email
    default_actions
  end
end

Thanks!

Answer

Evgenia Manolova picture Evgenia Manolova · Jan 31, 2013

according to this discussion: https://github.com/gregbell/active_admin/pull/623, if you don't want to use scopes, you can use the scoped collection method instead:

ActiveAdmin.register Business, { :sort_order => :name_asc } do
  scope :all, :default => true

  index do
    column :name
    column :type, :sortable => 'types.category'
    column :manager
    column :email
    default_actions
  end

  controller do
    def scoped_collection
      end_of_association_chain.includes(:type)
    end
  end
end