用条件搜索日期

时间:2011-04-28 22:53:05

标签: ruby-on-rails sphinx thinking-sphinx conditional-statements

我有一个模型,其中define块看起来像:

define_index do
  indexes title, content, manager, note, start_date, end_date

  has created_at, updated_at

  has user_id, :as => :user_id, :type => :integer

  set_property :delta => true
end

我想按日期搜索任务,这可能会落入start_date..end_date之间的差距,我该怎么做?

2 个答案:

答案 0 :(得分:0)

似乎像标准的Active Record SQL调用。由于您传递了参数,因此您可以像这样执行散列查询:

    tasks = Task.where("start_date > :start_date and end_date < :end_date", {:start_date => start_date, :end_date => end_date})

将其放在提供start_date和end_date的方法中,如下所示:

def tasks_within_range(start_date, end_date)
  Task.where("start_date > :start_date and end_date < :end_date {:start_date => start_date, :end_date => end_date})
end

你有一个动态的查找器! :)

答案 1 :(得分:0)

您希望将start_date和end_date作为属性,而不是字段:

define_index do
  indexes title, content, manager, note

  has created_at, updated_at, start_date, end_date
  has user_id, :as => :user_id, :type => :integer

  set_property :delta => true
end

然后,您将使用范围来限制这两个属性的结果:

today = Date.today.to_time # or whatever you like
Task.search :with => {
  :start_date => (Time.at(0)..date),
  :end_Date   => (date..Time.at(2 ** 32))
}

那应该做的 - 或者可能在第二个范围内添加+ 1.day。根据需要调整。