0

Hi I try to sort column on rails, activeadmin. The code is just like this.

# app/admin/users.rb
show do
  tab do
    table_for do
      # here comes my columns

I can find a good sorting solution from Sort a table_for in rails activeadmin. So I try this code and it works.

# app/admin/users.rb
show do
  tab do
    table_for user.supports.order(params[:order].gsub('_', ' ')), sortable: true do
      column 'step', sortable: :step do |support|
        support.step
      end

But how can I sort this column in the same table_for?

# app/admin/users.rb
column 'date', sortable: 'payment.date' do |support|
  support.payment.date
end

I tried a lot of things but cannot make it. My model code below.

# app/models/payment.rb
class Payment < ApplicationRecord
  belongs_to :support
# app/models/support.rb
class CampaignSupport < ApplicationRecord
  belongs_to :user
  has_many :payment
# app/models/user.rb
class User < ApplicationRecord
  has_many :support

Thanks

yalpsid
  • 13
  • 5

1 Answers1

0

Here is an example of something you could do (even if it's not ideal...):

# app/admin/users.rb
show do
  tab do
    # Use `split` in case you have columns like `created_at` (which won't work with `gsub('_', ' ')`)
    # In case `params[:order]` isn't defined, `step DESC` is the default order
    split_order = params[:order]&.split('_') || ['step', 'desc']
    order_direction = split_order.pop
    order_column = split_order.join('_')
    supports =
      user
        .supports
        .joins('LEFT JOIN payments ON payments.support_id = supports.id')
        .order(order_column => order_direction)

    table_for supports, sortable: true do
      column 'step', sortable: :step { |support| support.step }
      column 'date', sortable: 'payments.date' { |support| support.payment.date }
    end
  end
end
romainsalles
  • 2,051
  • 14
  • 17