gpt4 book ai didi

ruby-on-rails - Thinking sphinx - 带条件连接的索引 (has_and_belongs_to_many)

转载 作者:数据小太阳 更新时间:2023-10-29 07:07:06 25 4
gpt4 key购买 nike

我有模型 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

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

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))
=> ...

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

最佳答案

首先,您需要在服务索引定义中将服务类型 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 作用域与 Sphinx 一起使用 SphinxQL 查询 - 类似,但不完全相同)。

# 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')

关于ruby-on-rails - Thinking sphinx - 带条件连接的索引 (has_and_belongs_to_many),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23653831/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com