Search code examples
ruby-on-railsransackarel

How do I use the ransack gem to sort a table based on a model's instance method?


I am using Rails and the ransacker gem (2.3.2) to build out a table filterable by column name. I want to filter an account based on the first member of that account's email address. The models and instance method look like this:

class Account
 has_many :members

 def first_member_email
   members.order(created_at: :desc).first.email
 end
end

class Member
 belongs_to :account
end

I plan to use Ransack's "sort_link" to sort based on the account's first_member_email instance method. Based on the documentation it seems using a ransacker is the way to go. Something like this:

ransacker :first_member_email do |parent|
      Arel.sql(something)
 end

and in the view:

th=sort_link @q, :first_member_email, 'Created By'

but I can't get the Arel to work. What is the query here to get this to work, or is there another way without using Arel?


Solution

  • you can do like this:

    # app/models/account.rb
    
    class Account < ApplicationRecord
      scope :sort_by_first_member_email_asc, -> { sort_by(&:first_member_email) }
      scope :sort_by_first_member_email_desc, -> { sort_by(&:first_member_email).reverse }
    end
    

    If you want you can write custom query inside the scope. Thanks :)