【问题标题】:Ransack Search Id and Strings TogetherRansack 搜索 ID 和字符串一起
【发布时间】:2016-01-21 11:24:56
【问题描述】:

我正在尝试使用 Ransack 进行搜索,但是当我尝试将 id 和字符串一起搜索时遇到问题

:id_or_title_or_user_username_cont

它会产生错误

ActionView::Template::Error (PG::UndefinedFunction: ERROR: operator does not exist: integer ~~* integer

这个我也试过了

:id_eq_or_title_or_user_username_cont

它会产生以下错误

用于 Ransack::Search 的未定义方法 `id_eq_or_title_or_user_username_cont'

除了自定义谓词或自定义谓词之外,使用 ransack 一起搜索 id 和字符串的适当方法是什么?

【问题讨论】:

标签: ruby-on-rails ruby ransack predicates


【解决方案1】:

以下帖子Finding records by ID with Ransack提供了答案:


  # Cast the ID column to a string in PostgreSQL
  # when searching with Ransack.
  # Allows searches with _cont and _eq predicates.
  # From https://github.com/ernie/ransack/issues/224
  ransacker :id do
    Arel.sql("to_char(\"#{table_name}\".\"id\", '99999999')")
  end

提供的答案最初来自这个 github 问题:https://github.com/activerecord-hackery/ransack/issues/224

【讨论】:

    【解决方案2】:

    我需要比其他答案提供的更多细节,所以就在这里。

    _cont 对整数列的搜索不起作用,因为 LIKE 查询不适用于此类列。您需要将列从整数转换为字符串才能使查询正常工作。在您的模型中,您可以通过 ransacker 调用来做到这一点:

    # app/models/your_model.rb
    class YourModel
    
      # For Postgres
      ransacker :id do
        Arel.sql("to_char(\"#{table_name}\".\"id\", '99999999')")
      end
    
      # For MySQL
      ransacker :id do
        Arel.sql("CONVERT(`#{table_name}`.`id`, CHAR(8))")
      end
    
    

    然后您可以使用像id_cont 这样的搜索谓词。

    【讨论】:

      【解决方案3】:

      上面的答案正确的小更新,但我发现它们具有导致正常结果(例如完整列表,无搜索)按 ID 的字符串值排序的副作用,所以 - 1,10,11,12 ...等...2,20,21...3,30 等,而不是 1,2,3,4...

      所以结合上面的两个想法,可以按 ID 搜索,但仍然按 Int ID 排序

      在模型中创建一个字符串化版本的 ID 用于洗劫

      ransacker :id_as_str do
        Arel.sql("to_char(\"#{self.table_name}\".\"id\", '99999999')")
      end
      

      在形式上

      <%= f.search_field :id_as_str_or_some_other_stuff_cont, placeholder: "Search..." %>
      

      【讨论】:

        【解决方案4】:
        ransacker :id_to_s do 
          Arel.sql("regexp_replace(to_char(\"#{table_name}\".\"id\", '9999999'), ' ', '', 'g')")
        end
        

        【讨论】:

        • 感谢您的帮助。我在这里有点困惑,我应该如何在搜索字段中使用它?就像我的问题中的谓词可以用作 您能否进一步详细说明。将不胜感激。提前致谢
        • 所以@FakhirShad 如果您感到困惑,那么您不应该接受这个作为答案。
        • 查看我的评论日期和接受答案的日期@zozo
        猜你喜欢
        • 1970-01-01
        • 2015-01-24
        • 1970-01-01
        • 1970-01-01
        • 2015-02-28
        • 2015-09-24
        • 1970-01-01
        • 1970-01-01
        • 2014-10-21
        相关资源
        最近更新 更多