13

I am having these objects:

class District < ActiveRecord::Base
  belongs_to :city
end
class City < ActiveRecord::Base
  has_many :districts
end

What I would like to do (and been unable to do so thus far), is: have a City column in District's index and that column should be sortable on City.name.

Closest thing I was able to do without crashing ActiveAdmin is:

index do
  column City.human_name(:count => :other), :city, :sortable => :city_id
end

Which of course is not good enough; I don't want to sort on foreign key's integer value.

Tried stuff like :sortable => 'city.name', gives an error. Even tried to do it like you do it on "pure" Rails - :joins => :cities, :sortable => 'city.name' - no luck. Tried a bunch of other stupid stuff, got annoyed and decided to humbly ask for help.

Can anyone point me in the right direction? Thanks for your time.

dimitarvp
  • 2,316
  • 2
  • 20
  • 29

4 Answers4

25

That should also do the work:

index do
  column City.model_name.human, :city, :sortable => 'cities.name'
end

controller do
  def scoped_collection
    end_of_association_chain.includes(:city)
  end
end
Evgeniya Manolova
  • 2,542
  • 27
  • 21
10

Try this.. It will help....

index do
  column :city, :sortable => :"cities.name" do |district|
    district.city.human_name(:count => :other) if district.city.present?
  end
end

controller do
  def scoped_collection
    District.includes(:city)
  end
end
5

Very simple and readable solution:

index do
  column :city, sortable: "cities.name"
end

controller do
  def scoped_collection
    # join cities
    super.includes :city
  end
end
Grantzau
  • 1,664
  • 1
  • 12
  • 6
2

Use the name of the table, probably cities. It might look like this:

District.joins(:city).order("cities.name")
bricker
  • 8,911
  • 2
  • 44
  • 54
  • 2
    I know this. I meant ActiveAdmin's DSL, though. Happily, it got fixed like 14 hours ago -- https://github.com/gregbell/active_admin/pull/623 – dimitarvp Oct 16 '11 at 06:59