Problem with WHERE clause for STI models #353

kot-begemot opened this Issue Apr 26, 2012 · 1 comment


None yet

2 participants

Here is a brief description of the problem we faced:

Model Structure is as follows:

class User < ActiveRecord::Base

class Employee < User
   define_index do
    indexes name
    indexes subjects(:id), as: :subject_ids
    indexes subjects(:name), as: :subject_names

    has, as: :city

class Tutor < Employee

class AcademyTutor < Employee

Here Employee class is used as a proxy class, so no actual record is saved with 'Employee' type. That was the problem, as generated configuration contains following:

source employee_core_0
  sql_query = ... WHERE "users"."type" IN ('Employee', 'AcademyTutor', 'Tutor') AND ("users"."id" >= $start AND "users"."id" <= $end AND "users"."type" = 'Employee') ...

As it clearly seen from here where clause contains two things:

  • WHERE "users"."type" IN ('Employee', 'AcademyTutor', 'Tutor') is generated by ActiveRecord::Relation
  • "users"."id" >= $start AND "users"."id" <= $end AND "users"."type" = 'Employee' generated by Thinking sphinx

So having "users"."type" = 'Employee' part is not compulsory and in fact obstruct indexing process in this case. This part is added during the source initialization:

module ThinkingSphinx
  class Source
    def initialize(index, options = {})
      unless @model.descends_from_active_record?
        stored_class = @model.store_full_sti_class ? :
        @conditions << "#{@model.quoted_table_name}.#{quote_column(@model.inheritance_column)} = '#{stored_class}'"

Its being added into conditions in this case, and later interfere with sql. This part is a bit unclear for us, as in case of a User model being indexed, it will not take a play. On the other hand, ActiveRecord::Relation (for rails >= 3.0, can't tell anything about lower versions) includes that by default if it is compulsory. Hence (at least for Rails 3.0 and above) we guess it can be ignored.

Actually, 2.0.11 anyway dependent on activerecord 3.0.3. In that case type condition is not required, as it will be there anyway.

@kot-begemot kot-begemot pushed a commit to kot-begemot/thinking-sphinx that referenced this issue May 4, 2012
E-Max [#353] Added test for Inherited and decendent model ddf20d9
@pat pat closed this in d26aac8 May 10, 2012
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment