3

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?

Yoni Baciu
  • 2,667
  • 1
  • 22
  • 28

2 Answers2

5

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.

Yoni Baciu
  • 2,667
  • 1
  • 22
  • 28
0

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.

Ashish Gaur
  • 2,030
  • 2
  • 18
  • 32