2017-08-16 66 views
0

我正在尝试创建一个Rails控制器查询,该查询可以查找最近日期不在将来的列中的记录(这就是为什么我无法做到简单order声明)。我发现this post,但答案(MyModel.where("created_at < ?", 2.days.ago))引发了一些错误。查找最近的Rails记录过去

我有这个工作正常,但如果开始在它选择未来一周有说,不是最近的一个过去:

@most_recent = Plan.order("week_starting").last 

任何想法,以如何做到这一点正确Rails的?

这里是我的整个plans#index方法:

def index 
    @plans = Plan.where(user_id: current_user.id) 
    @plan = Plan.new 
    @recent = Plan.order("week_starting").last <<<THIS LINE 
    @recipes = Recipe.where(user_id: current_user.id) 
    @monday = Recipe.where(id: @recent.monday)[0] 
    @tuesday = Recipe.where(id: @recent.tuesday)[0] 
    @wednesday = Recipe.where(id: @recent.wednesday)[0] 
    @thursday = Recipe.where(id: @recent.thursday)[0] 
    @friday = Recipe.where(id: @recent.friday)[0] 
    @saturday = Recipe.where(id: @recent.saturday)[0] 
    @sunday = Recipe.where(id: @recent.sunday)[0] 
    end 

基本上,我需要的​​为它具有week_starting值最接近Date.today仍然在过去的当前用户。

回答

0

入住这

Plan.where("created_at > ?", Time.now.beginning_of_week).order("week_starting").last 
+0

这可能不是很清楚,但我正在寻找最近的未来记录。这两天的事情只是一个来自另一个问题的例子... – Liz

+0

随着你的代码(改编),我认为这会产生像'Plan.where(“week_starting <?”,Time.now).limit(1)',这给了我一个错误,说'未定义的方法'week_starting'为#' – Liz

+0

是计划表中的week_starting字段? –

0

这是否对你的作品?

MyModel.where("created_at < ? ", Time.now).order('created_at DESC').first 

不知道你为什么有week_starting那是什么。但为了获得最近的记录,它应该足够了