rails has_scope and sphinx search



在我的应用程序中,我使用 gem 和 thinking sphinx has_scope ,在模型中,我写了类似的东西:

scope :by_description, -> description { where("description like ?", "%#{description}%") if description.present?}

然后,在控制器中:

has_scope :by_description
def somemimimi
  @cars = apply_scopes(Car).order(created_at: :desc).page(params[:page]).per(20)
end

但是当我试图写这样的东西时:

scope :by_description, -> description { search description}

我收到以下错误

 you cannot search with Sphinx through ActiveRecord scopes

但我也只是用狮身人面像搜索(当这个参数出现时),我该如何解决这个问题?

我不确定has_scope gem 是否适用于思考狮身人面像范围,但您可以在模型中尝试以下操作(替换现有的 ActiveRecord 范围):

include ThinkingSphinx::Scopes
sphinx_scope(:by_description) { |description| description }

但请记住,此作用域返回的是思考狮身人面像搜索对象,而不是 ActiveRecord 关系,因此您不能将其与 ActiveRecord 方法(如 whereorder)结合使用(您也不能在其上调用任何 ActiveRecord 作用域)。因此,在控制器中apply_scopes调用后,您需要调整链接的内容。也许如下:

@cars = apply_scopes(Car).search(order: 'created_at DESC', page: params[:page], per_page: 20)

但是,这一切都建立在以下假设之上:has_scope gem 的方法非常简单,它只会在给定模型上调用类级方法,无论它们是否是 ActiveRecord 范围。

从避免has_scope gem 更改引起的问题的角度来看,我建议不要将其与 Thinking Sphinx 查询一起使用。

最新更新