Search code examples
ruby-on-railsrubysphinxthinking-sphinx

How check that associated file is not NULL in thinking sphinx?


I have a Product model that has_many :images

Image model has a photo field (I use carrierwave gem to store the file):

class Image < ApplicationRecord
  mount_uploader :photo, DressingUploader
end

Here is my product_index.rb file:

ThinkingSphinx::Index.define :product, with: :active_record do
  indexes name

  has images.pose, as: :image_pose

  join images
end

How can I add images.photo attribute to thinking sphinx which will check whether the photo is present or not? I could add this line where "images.photo IS NOT NULL", but I do not need the condition to work globally.

I tried to do something like

has "images.photo IS NOT NULL", as: :has_photo, type: :boolean

But it doesn`t work


Solution

  • Because you're dealing with many images for a given product, you'll need to aggregate the photo values for each image. It could be that a SUM(CASE) statement will do the job (and this should work in both MySQL and PostgreSQL):

    has "SUM(CASE WHEN images.photo IS NULL THEN 0 ELSE 1 END) > 0",
      as: :has_photo, type: :boolean
    

    This solution is fine for SQL-backed indices (which is what you're using). For anyone coming across this that is using real-time indices, then the solution is different… you'll want a method to refer to within your class:

    def has_image_photos
      images.any? { |image| image.photo.present? }
    end
    

    And then in the index:

    has has_image_photos, as: :has_photo, type: :boolean