简体   繁体   English

使用ransacker进行自定义搜索

[英]Custom search with ransacker

I'm trying to add a custom filter to ActiveAdmin which is powered by Ransack these days. 我正在尝试向ActiveAdmin添加自定义过滤器,这些过滤器最近由Ransack提供支持。 Unfortunately, ransacker is not documented at all and from the few resources online I fumbled together the following (in the User model): 遗憾的是, ransacker根本没有记录,而且从网上的少量资源中我偶然发现了以下内容(在用户模型中):

ransacker :full_text, formatter: ->(search) {
  ids = User.search_in_all_translated(search).map(&:id)
  ids = ids.any? ? ids : nil
} do |parent|
  parent.table[:id]
end

The search_in_all_translated method returns an array of users which match the search string across all translated attributes. search_in_all_translated方法返回一个用户数组,该数组与所有已翻译属性中的搜索字符串匹配。

On the admin page, the following filter is defined: 在管理页面上,定义了以下过滤器:

filter :full_text_in,
  label: 'full text search',
  as: :string

The filter itself works, so filtering tom will list all matching records. 过滤器本身可以工作,因此过滤tom会列出所有匹配的记录。 However, the value in the filter input switches to ["tom"] . 但是,滤波器输入中的值切换为["tom"]

Before applying the filter: 在应用过滤器之前:

在此输入图像描述

After applying the filter: 应用过滤器后:

在此输入图像描述

Any ideas how to fix this? 任何想法如何解决这一问题?

There's a feature for ransackable scopes waiting to be merged: https://github.com/activerecord-hackery/ransack/pull/288 可转换的范围有一个等待合并的功能: https//github.com/activerecord-hackery/ransack/pull/288

UPDATE: 更新:

I've given the work of avit and glebm another go with PR https://github.com/activerecord-hackery/ransack/pull/390 which has been merged, it's therefore now possible to use scopes with Ransack. 我已经将avit和glebm的工作另外与PR https://github.com/activerecord-hackery/ransack/pull/390合并了,因此现在可以将范围与Ransack一起使用。 For the documentation, see the commit: 有关文档,请参阅提交:

https://github.com/svoop/ransack/commit/72dd5d12d58919bf37199234cf13f9533f3b8cd5 https://github.com/svoop/ransack/commit/72dd5d12d58919bf37199234cf13f9533f3b8cd5

Here's a real-life example: 这是一个真实的例子:

class Project < ActiveRecord::Base
  scope :full_text_search, ->(search) { search_in_all_translated(search) }

  def self.ransackable_scopes(auth_object = nil)
    [:full_text_search]
  end
end

In this example search_in_all_translated returns some complex indexed full text search SQL. 在此示例中, search_in_all_translated返回一些复杂的索引全文搜索SQL。

in or cont_any do a search via an array. incont_any通过数组进行搜索。 So in this case, it's doing a search Model.where(something: ["tom", "tom1", "tom2"] and because of the way the params[:q] works, it returns it to your input as an array. A quick and dirty fix I did to help user experience is added value: nil, to the input form 所以在这种情况下,它正在搜索Model.where(something: ["tom", "tom1", "tom2"]并且由于params [:q]的工作方式,它将它作为数组返回到您的输入我为帮助用户体验所做的快速而肮脏的修复是增值value: nil,输入表单

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

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