【问题标题】:Thinking sphinx - index for join with condition (has_and_belongs_to_many)Thinking sphinx - 条件连接索引 (has_and_belongs_to_many)
【发布时间】:2014-05-14 11:47:05
【问题描述】:

我有模型Service,它具有按服务类型ID过滤服务的范围:

class Service < ActiveRecord::Base
  has_and_belongs_to_many :service_types  

  scope :by_service_types, -> ids { joins(:service_types).where('service_types_services.service_type_id in (?)', ids) }
end

class ServiceType < ActiveRecord::Base
  has_and_belongs_to_many :services
end

所以,当我运行范围时,我会得到这样的结果:

Service.by_service_types([54])
  Service Load (0.8ms)  SELECT "services".* FROM "services" INNER JOIN "service_types_services" ON "service_types_services"."service_id" = "services"."id" INNER JOIN "service_types" ON "service_types"."id" = "service_types_services"."service_type_id" WHERE "services"."deleted" = 'f' AND (service_types_services.service_type_id in (54))
 => ...

如何构建属性来为此类范围构建索引?

【问题讨论】:

    标签: ruby-on-rails ruby thinking-sphinx


    【解决方案1】:

    首先,您需要将服务类型 ID 作为服务索引定义中的多值属性:

    ThinkingSphinx::Index.define(:service, :with => :active_record) do
      # ... existing index definition
    
      has service_types.id, :as => :service_type_ids
    end
    

    然后你可以搜索并使用该属性:

    Service.search(:with => {:service_type_ids => 54})
    

    如果您想将其包装到 ActiveRecord 范围之类的东西中,Thinking Sphinx 有自己的范围功能(两者不能组合,因为 ActiveRecord 与使用 SQL 查询的数据库一起使用,但 Sphinx 范围与使用 SphinxQL 查询的 Sphinx 一起使用 - 类似,但不完全相同)。

    # include this in your model:
    include ThinkingSphinx::Scopes
    
    sphinx_scope(:search_by_service_type) { |ids|
      {:with => {:service_type_ids => ids}}
    }
    

    然后搜索:

    Service.search_by_service_type(54)
    # You can chain further search arguments onto the scope:
    Service.search_by_service_type(54).search('foo', :order => 'created_at DESC')
    

    【讨论】:

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