简体   繁体   English

如何使用 ransack gem 根据模型的实例方法对表进行排序?

[英]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.我正在使用 Rails 和 ransacker gem (2.3.2) 来构建一个可按列名过滤的表。 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.我打算使用 Ransack 的“sort_link”根据账户的 first_member_email 实例方法进行排序。 Based on the documentation it seems using a ransacker is the way to go.根据文档,使用 ransacker 似乎是可行的方法。 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.但我无法让 Arel 工作。 What is the query here to get this to work, or is there another way without using Arel?这里的查询是什么让这个工作,或者有没有不使用 Arel 的另一种方法?

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 :)谢谢 :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM