I have the such model:
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
It has polymorphic association with Attachments. To grab all services with images I use scope above. It generates such request:
> 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'
But I don't have any idea how do same search via Thinking Sphinx. Any ideas?
What I would do here is create a boolean attribute via a custom SQL snippet:
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
Then searching becomes the following:
Service.search with: {has_images: true}
It's worth noting that the table name in the SQL snippet may not be accurate if you're already joining against the attachments table via a different association. If this is the case, have a look at the generated sql_query value for the source service_core_0
in config/development.sphinx.conf
and use the appropriate table/alias as required.