Rails 4 - 思考 - 狮身人面像日期范围

时间:2014-08-10 18:27:56

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

我有一个模型对象,它有一个开始和结束日期。在搜索时,我想添加一个条件,我只能获得start_date之前的Time.nowend_date之后的Time.now的对象,即是ongoing

我尝试了以下内容:

@team = Team.find_by_id(params[:team_id])

# start_date and end_date are properties on my model object, that I want to filter based on.
@competitions = @team.competitions.search(params[:search], conditions: { :start_date => start_date..Time.now.to_i, :end_date => end_date..Time.now.to_i }, :page => params[:page], :per_page => 10, :order => 'created_at DESC')

这会导致以下错误:

undefined local variable or method `start_date'

关于我应该采取哪些措施来获得我想要的行为?

1 个答案:

答案 0 :(得分:3)

也许这样的事情可以解决问题:

@competitions = @team.competitions.search params[:search],
  :select   => '*, start_date < NOW() AND end_date > NOW() as current',
  :with     => {:current => true},
  :page     => params[:page],
  :per_page => 10,
  :order    => 'created_at DESC'

这会动态生成自定义属性(current),然后按此过滤。