【问题标题】:Rails Search with queryRails 使用查询进行搜索
【发布时间】:2014-02-04 04:55:04
【问题描述】:

我想根据传递给模型的参数过滤作业,目前搜索可以完美地工作,没有将查询传递给模型,但是当我输入查询时它不会返回任何内容。如何使用查询和条件执行此查询。 结果 。任何想法都会非常感激。

module Refinery
  class SearchEngine
    # How many results should we show per page
    RESULTS_LIMIT = 100

    # Perform search over the specified models

    def self.search(query, job_region, job_division, country, job_type, page = 1)
      results = []

      Refinery.searchable_models.each do |model|

      criteria = {:job_region => job_region,
                    :job_division => job_division,
                    :country => country,
                    :job_type => job_type

        }.select { |key, value| value.present? }


        if query.present?
          results << model.with_query(query).where(criteria)
        else
          results << model.limit(RESULTS_LIMIT).where(criteria)
        end

      end

      results.flatten[0..(RESULTS_LIMIT - 1)]
    end

  end
end

【问题讨论】:

  • “查询”的预期内容是什么?原始 SQL?条件哈希?
  • 条件哈希,如果没有查询传入模型,它会返回预期的结果,但是 with_query 它不起作用。我正在使用 act_as_index gem 来执行查询搜索。
  • 这可能听起来很愚蠢,但请尝试另一种方式:model.where(criteria).with_query(query)(其中返回一个 ActiveRecord::Relation,它能够链接范围,也许 .with_query 只返回一个数组)
  • Yoshiji 先生,这并不愚蠢,这很神奇 :-)。它现在正在工作。非常感谢您的时间。谢谢

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-4 ruby-on-rails-3.1


【解决方案1】:

这里的问题是.with_query(qry) 方法返回一个数组。你想做链式作用域,所以你必须使用返回 ActiveRecord::Relation 对象的作用域。

model.with_query(query) 
# returns an Array

model.with_query(query).where(criteria) 
# calling .where on an Array object => NoMethodError

model.where(criteria) 
# returns an ActiveRecord::Relation

model.where(criteria).with_query(query) 
# calls the query on an AR::Relation object, which is doable

短版:更改:

results << model.with_query(query).where(criteria)

到这里:

results << model.where(criteria).with_query(query)

【讨论】:

    猜你喜欢
    • 2014-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-30
    • 2014-10-14
    • 1970-01-01
    • 1970-01-01
    • 2018-11-06
    相关资源
    最近更新 更多