ActiveAdmin: sort by child association's property

前端 未结 4 1426
太阳男子
太阳男子 2021-02-13 17:08

I am having these objects:

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


        
相关标签:
4条回答
  • 2021-02-13 17:13

    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
    
    0 讨论(0)
  • 2021-02-13 17:21

    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
    
    0 讨论(0)
  • 2021-02-13 17:34

    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
    
    0 讨论(0)
  • 2021-02-13 17:34

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

    District.joins(:city).order("cities.name")
    
    0 讨论(0)
提交回复
热议问题