使用ransacker进行自定义搜索 [英] Custom search with ransacker

查看:160
本文介绍了使用ransacker进行自定义搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这些天,我正在尝试向ActiveAdmin添加自定义过滤器,该过滤器由Ransack提供支持。不幸的是,根本没有记录 ransacker ,从网上的一些资源中,我摸索了以下内容(在用户模型中):

I'm trying to add a custom filter to ActiveAdmin which is powered by Ransack these days. Unfortunately, ransacker is not documented at all and from the few resources online I fumbled together the following (in the User model):

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

search_in_all_translated 方法返回匹配所有已翻译属性中搜索字符串的用户数组。

The search_in_all_translated method returns an array of users which match the search string across all translated attributes.

在管理页面上,以下过滤器为定义:

On the admin page, the following filter is defined:

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

过滤器本身有效,因此过滤 tom 将列出所有匹配的记录。但是,过滤器输入中的值切换为 [ tom]

The filter itself works, so filtering tom will list all matching records. However, the value in the filter input switches to ["tom"].

在应用过滤器之前:

应用过滤器后:

有什么办法解决此问题?

Any ideas how to fix this?

推荐答案

有一个可等待合并的可洗范围的功能:
https:// github .com / activerecord-hackery / ransack / pull / 288

There's a feature for ransackable scopes waiting to be merged: https://github.com/activerecord-hackery/ransack/pull/288

更新:

我已将PR和 https://github.com/activerecord-hackery/ransack/交给了avit和glebm pull / 390 已被合并,因此现在可以在Ransack中使用范围。有关文档,请参见提交:

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. For the documentation, see the commit:

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

这是一个真实的示例:

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

在此示例中, search_in_all_translated 返回一些复杂的索引全文搜索SQL。

In this example search_in_all_translated returns some complex indexed full text search SQL.

这篇关于使用ransacker进行自定义搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆