So I'm using Thinking Sphinx to handle searching my User database.
I have dateofbirth in my database and age defined in my User model with this helper (Courtesy of Stackoverflow of course :)
def age
(Time.now.to_s(:number).to_i - dateofbirth.to_time.to_s(:number).to_i)/10e9.to_i
end
However I cant figure out how I can index the users age. Heres how I'm indexing in User.rb
define_index do
indexes users
indexes :firstname, sortable: true
indexes :dateofbirth, sortable: true
indexes :location, sortable: true
end
The error I get is 'undefined method `to_time' for nil:NilClass'. I can see to_time in the age helper, but still nonethewiser as what to do.
Sphinx - when used by Thinking Sphinx without real-time indices - only gathers data via SQL statements. Given you're using the legacy define_index method, you're definitely not using real-time indices, and so you'll need to find a way to represent someone's age via a SQL snippet.
This answer is a good starting point, but would need to be adapted to either MySQL or PostgreSQL (as you're almost certainly using one of those).
Once you figure something out, you can then add it to your index with something like the following:
define_index do
indexes users
indexes firstname, location, sortable: true
has "SQL SNIPPET GOES HERE", as: :age, type: :integer
end
The has
method is used because attributes are sortable by their very nature, and I'm guessing you wouldn't expect to get a user back by searching for their age in a text box? If I'm wrong, then change it to indexes
and remove the type
option (all fields are strings).