Search code examples
ruby-on-railsthinking-sphinx

Thinking Sphinx indexer condition


My models:

class Item < ActiveRecord::Base
    belongs_to :group
    scope :able, ->{joins(:group).where(:groups => {:disabled => [nil,false]}).order("position")}
end

class Group < ActiveRecord::Base
    has_many :items
    scope :able, ->{ where(disabled: [false,nil]).order('position') }
end

My item_index.rb

ThinkingSphinx::Index.define :item, :with => :active_record do
  indexes title
  # attributes
  has created_at, updated_at, group_id, position
end

How i can index only Item where group.disabled is false or nil.

Example with where:

ThinkingSphinx::Index.define :item, :with => :active_record do
  where "id = 1"
  indexes title
  # attributes
  has created_at, updated_at, group_id, position
end

This will index only Item with id = 1


Solution

  • In your index definition:

    # force join on groups table:
    join group
    
    # PostgreSQL
    where "disabled = 'f' OR disabled IS NULL"
    
    # MySQL
    where "disabled = 0 OR disabled IS NULL"
    

    I'd highly recommend on having a default value of true or false for your disabled column, thus avoiding null values.