我想在传递给模型的参数上过滤作业,目前搜索工作完美无需查询传递到模型中,但是当我输入查询时它不会返回任何内容。如何使用查询和条件执行此查询。 结果<< model.with_query(查询)。凡(条件)即可。任何想法都会非常感激。
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
答案 0 :(得分: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)