Yoni Baciu
Yoni Baciu

Reputation: 2707

Thinking Sphinx application-wide search: filtering by an attribute that only exist in some models

I want to search on multiple models and filter by a certain attribute that some models have and some do not. I want the models with the attribute to get filtered but the ones without it to just ignore it.

Currently only the models with the attribute will return results. Is there a way to make the other models return results as well by somehow ignoring the attribute filter?

Upvotes: 3

Views: 855

Answers (2)

Ashish Gaur
Ashish Gaur

Reputation: 2050

I had to do this in a default_sphinx_scope and the application being too big I couldn't check every model and do that for those who have doesn't have the attribute. So I did it with following:

class User

  ...

  sphinx_scope(:active_only) do
    if self.respond_to?(:status)
      {:with => {:status => true}}
    else
      {}
    end
  end
  default_sphinx_scope(:active_only)

  ...
end

It applied the scope only when the status column was present. Cheers.

Upvotes: 0

Yoni Baciu
Yoni Baciu

Reputation: 2707

Found a way to do it. On the indexes of the models that do not have such an attribute, a dummy one can be created like so:

has "0", :type => :integer, :as => :the_attribute_name

Then when performing the application-wide search:

@results = ThinkingSphinx.search(@search_term, 
  :with => {:the_attribute_name => [@the_attribute_value, 0]}
)

Btw, this assumes that a zero value is not allowed on the models that do have this attribute. If zero is a valid attribute in those model then another value (e.g. 9999999) can be used. Be aware that attributes cannot accept negative integers.

Upvotes: 5

Related Questions