rails Sphinx search with optional params ERROR: sphinxql: syntax error, unexpected AND, expecting CONST_INT (or 3 other tokens)

StackOverflow https://stackoverflow.com/questions/21099684

Question

rake ts:rebuild execute without error, but i can't get the index page to show i have this error:

sphinxql: syntax error, unexpected AND, expecting CONST_INT (or 3 other tokens) near 'AND `broadcast_date` BETWEEN 0 AND 0 AND `sphinx_deleted` = 0 LIMIT 0, 20; SHOW META'   

controller

 @segments = Segment.search params[:name], :with => { :person_id => params[:person_ids] ,:broadcast_date => dbDateFrom.to_i..dbDateTo.to_i}, :page => params[:page], :per_page => 20    

model

class Segment < ActiveRecord::Base
   attr_accessible :broadcast_date, :comment, :name, :person_id, :segment, :tv_show_id, :person_ids,:balance    
   belongs_to :episodes
   has_many :personSegments
   has_many :people , :through => :personSegments
    before_save :compute_balance
end    

index

ThinkingSphinx::Index.define :segment, :with => :active_record do
  indexes name, :sortable => true

  has created_at, updated_at 
  has broadcast_date
  has people(:id), :as => person_id
end   

on index page the params are empty. where is the problem? It seems like it is waiting for the values for person_id but it's optional on the form.

UPDATE*
Got it to work with:

unless params[:person_ids].blank?
  condition =  { :broadcast_date => dbDateFrom.to_i..dbDateTo.to_i, :person_id => params[:person_ids] }
else
  condition =  { :broadcast_date => dbDateFrom.to_i..dbDateTo.to_i }
end    

@segments = Segment.search params[:name], :with=> condition ,:page => params[:page], :per_page => 20   
Was it helpful?

Solution

At this point in time, Thinking Sphinx creates filters for each key/value pair in the :with hash, whether or not the value is nil. So, it's better if you create your search request a little more dynamically:

filters = {:broadcast_date => dbDateFrom.to_i..dbDateTo.to_i}
filters[:person_id] = params[:person_ids] if params[:person_ids].present?

@segments = Segment.search params[:name],
  :with     => filters,
  :page     => params[:page],
  :per_page => 20
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top