Search code examples
ruby-on-railsrubythinking-sphinx

Working with Thinking Sphinx and dates


I'm building an app that has posts with expiration dates, and using Thinking Sphinx as the search tool.

Basically, what I'm looking for is a way when doing the search, to filter out all the posts that are expired

So basically apply this

@posts = Post.where('expiration > ?', DateTime.now)

to this

@posts = Post.search(params[:search])

Here's my index file

ThinkingSphinx::Index.define :post, :with => :active_record do
    indexes :title
    indexes :duties
    indexes :experience
    has employer_id, expiration, created_at
end

Solution

  • It's easiest to replace less-than/greater-than logic with ranges... and in this case, a range plus an exclusive (rather than inclusive) filter should do the trick:

    @posts = Post.search params[:search], :without => {:expiration => 0..Time.zone.now.to_i}
    

    Sphinx stores times as UNIX timestamps, hence it's possible to use integers in the filter.