Rails 3 ActiveAdmin. How to set a default sort order for an associated record?

爷,独闯天下 提交于 2019-12-21 20:18:19

问题


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.



来源:https://stackoverflow.com/questions/9487477/rails-3-activeadmin-how-to-set-a-default-sort-order-for-an-associated-record

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