Rails 3 ActiveAdmin. How to set a default sort ord

2020-07-22 19:08发布

问题:

I have a shipments model and an invoice model. The invoice belongs to shipment.

So I added a default sort order for shipment like this...

config.sort_order = 'file_number_desc'

But now I want to add the same sort order for invoices, (shipments table is the one that has the file_number column) but this doesn't seem to work:

config.sort_order = 'shipments.file_number_desc'

回答1:

Nice solution @Siwei, I would just use, instead of the scope :joined which by default shows a filter on top of the list called Joined, the following:

controller do
  def scoped_collection
    GenericItem.includes(:vendor)
  end
end

Which modifies the ActiveAdmin controller to use that scope as default, without showing it to the user.



回答2:

according to this post on its official website(I am wondering why the maintainer hasn't include this import post to the document ^_^ ): https://github.com/gregbell/active_admin/pull/623

Step1. assuming you have "generic_items" belongs to "vendor", and vendor has an attribute:name.

# app/models/generic_item.rb
class GenericItem < ActiveRecord::Base
  belongs_to :vendor
end

# app/models/vendor.rb
class Vendor < ActiveRecord::Base
  has_many :generic_items
  # attr_accessor: name
end

Step2. now you want to make an order of "vendor.name" in your "admin/generic_items" page.

# app/admin/generic_items.rb
ActiveAdmin.register GenericItem do

  scope :joined, :default => true do |generic_items|
    generic_items.includes [:vendor]
  end 

  index do 
    # other column definition... 
    column :vendor_id, :sortable => "vendors.name" do |generic_item|
      generic_item.vendor.name if generic_item.vendor
    end
  end
end  

P.S. however the filter will down once you do this. for now. hope this issue could be fixed ASAP.