我有这样的模型:
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'
但是我不知道如何通过Think Sphinx进行相同的搜索。有任何想法吗?
我在这里要做的是通过自定义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代码段中的表名可能不正确。如果是这种情况,请查看为源生成的sql_query值service_core_0
,config/development.sphinx.conf
并根据需要使用适当的表/别名。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句