我有这样的模特:
class Service < ActiveRecord::Base
has_many :images, -> { where attachment_type: 'image' }, class_name: 'Attachment', as: :attachable, dependent: :destroy
scope :with_images, -> { joins(:images).uniq }
end
它与附件具有多态关联。要使用图像获取所有服务,我使用上面的范围。它会产生这样的请求:
> Service.with_images
Service Load (25.6ms)
SELECT DISTINCT "services".* FROM "services" INNER JOIN "attachments" ON "attachments"."attachable_id" = "services"."id" AND "attachments"."attachable_type" = 'Service' AND "attachments"."attachment_type" = 'image' WHERE "services"."deleted" = 'f'
但我不知道如何通过Thinking Sphinx进行同样的搜索。有什么想法吗?
答案 0 :(得分:1)
我在这里要做的是通过自定义SQL片段创建一个布尔属性:
has "COUNT(attachments.id) > 0", as: :has_images, type: :boolean
join images # need to force the join if it's not used through normal method chaining
然后搜索成为以下内容:
Service.search with: {has_images: true}
值得注意的是,如果您已经通过其他关联加入了附件表,则SQL代码段中的表名可能不准确。如果是这种情况,请查看service_core_0
中生成的源config/development.sphinx.conf
的sql_query值,并根据需要使用相应的表/别名。