【问题标题】:rails has_scope and sphinx searchrails has_scope 和 sphinx 搜索
【发布时间】:2014-04-01 07:32:58
【问题描述】:

在我的应用程序中,我使用has_scope gem 和thinking sphinx,在模型中我写了如下内容:

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

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

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 thinking-sphinx has-scope


    【解决方案1】:

    我不确定 has_scope gem 是否可以与 Thinking Sphinx 范围一起使用,但您可以在模型中尝试以下操作(它会替换您现有的 ActiveRecord 范围):

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

    但请记住,此范围返回的是 Thinking Sphinx 搜索对象,而不是 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 查询一起使用。

    【讨论】:

    • 但是如何使用范围和 morf.search?
    • @cars = apply_scopes(Car).search(order: 'description DESC', page: params[:page], per_page: 20) 有效,但是当我更改为 created_at - 不,但是如何在不向索引添加字段的情况下进行排序搜索?
    • 在搜索调用中排序的任何内容都必须是属性(或可排序字段)。 Sphinx 只能使用其索引中可用的数据进行排序。
    • 如果还有其他问题,也许值得开始另一个问题?很难在评论线程中讨论细节(错误消息、堆栈跟踪、索引定义、gem 版本等)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-12
    • 1970-01-01
    相关资源
    最近更新 更多