Ruby on rails 可选时间where子句

Ruby on rails 可选时间where子句,ruby-on-rails,ruby,rails-activerecord,Ruby On Rails,Ruby,Rails Activerecord,我有一个可选的time where子句 即where('created_at

我有一个可选的time where子句

where('created_at<?',params[:infinite_scroll_time_buffer])

这包括在一系列调用中

我意识到,
where
可以采用散列,如果散列为空,或者缺少任何属性,它们将不会被包括在内。这听起来很棒,因为我可以避免检查
参数[:infinite\u scroll\u time\u buffer]
是否存在,只需包含
where
子句,让Rails处理其余部分

问题如下:

def action
  options = {}
  options[:created_at] = params[:infinite_scroll_time_buffer]

  Post.method.another_method.where(options).another_method
end
除了SQL查询检查
post.created_at=?
而不是
post.created_at<?
(这是正确的)之外,这是可行的

我可以有一系列的时间,但我一生都找不到一种时间的方式来引用所有时间的开始,或者类似于
时间::一切的开始\u我们知道\u DUN\u DUN\u DUN


这样我就可以有一个从这个到
参数[:infinite\u scroll\u time\u buffer]
的范围。有没有其他方法可以做到这一点

在post.rb中创建一个范围:

如果不存在
参数[:无限滚动\u时间\u缓冲区]
则首先不要进行查询:

def action
  options = {}
  # more operation on options hash here
  posts = Post.method.another_method.where(options)
  posts = posts.created_before(params[:infinite_scroll_time_buffer]) if params[:infinite_scroll_time_buffer].present?
  posts = posts.some_another_method
end

我认为你有语法错误。你打算怎么处理选项?更正<代码>->(时间){where('created_at<?',time)}将创建lambda。另外,在action方法中,为了可读性,我将表达式拆分为多行。您的
操作
方法中有
选项
,因此我假设您倾向于在您给出的示例下面的其他查询中使用它。我遗漏了什么?当我使用该方法并且
参数[:infinite\u scroll\u time\u buffer]
为nil时,我在SQL查询中
处创建了\u,而不是根本没有发生。通过以下方式修复了它:
范围:在之前创建,,>(time=nil){where('created\u at
@David:如果参数一开始不存在,为什么要传递它?即使您这样做,您的代码
选项[:created_at]=params[:infinite_scroll\u time\u buffer]
是否也会有同样的效果?它将进行查询:
where created\u at为NULL
def action
  options = {}
  Post.method.another_method.where(options).
      created_before(params[:infinite_scroll_time_buffer]).
      another_method
end
def action
  options = {}
  # more operation on options hash here
  posts = Post.method.another_method.where(options)
  posts = posts.created_before(params[:infinite_scroll_time_buffer]) if params[:infinite_scroll_time_buffer].present?
  posts = posts.some_another_method
end