【问题标题】:How to return ActiveRecord WhereChain as a standard relation?如何将 ActiveRecord WhereChain 作为标准关系返回?
【发布时间】:2022-02-09 03:19:27
【问题描述】:

我有这个范围正在执行产品搜索。问题是当我只需要 Product 对象的标准关系数组时,它会返回 ActiveRecord::QueryMethods::WhereChain

我认为我不能使用标准 .where() 来实现我在这里尝试做的事情。这可行,但是,它返回了我不想要的 wherechain。

scope :product_search, -> (query) {
    I18n.transliterate(query)
        .downcase
        .gsub(/\s+/, ' ')
        .gsub(/[^\w\s]/, '')
        .split(' ')
        .map{ |w| "%#{w}%" }
        .reduce(self) do |dataset, word|
        binding.pry
      dataset.where{ product_search_format(full_title).like word }
    end
  }

作为参考,product_search_format 是数据库中的索引:

      t.index "product_search_format((full_title)::text) gin_trgm_ops", name: "app_products_full_title_search_idx", using: :gin

【问题讨论】:

    标签: ruby-on-rails ruby activerecord sinatra


    【解决方案1】:

    据我了解,您需要这样的东西

    scope :product_search, ->(query) do
      pattern =
        I18n.transliterate(query)
          .downcase
          .gsub(/\s+/, ' ')
          .gsub(/[^\w\s]/, '')
          .split
          .join("|")
    
      where('product_search_format(full_title) ~ :pattern', pattern: pattern)
    end
    

    不带 args 的 BTW 拆分可用作分词器(将字符串拆分为单词)

    ~ 运算符是 PostgreSQL 中的匹配运算符,您可以使用 LIKE%-matchers 代替它

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多