查找过去最新的 Rails 记录



>我正在尝试创建一个 Rails 控制器查询,该查询查找列中最近日期的记录,而不是将来的列(这就是为什么我不能做一个简单的order语句(。 我找到了这篇文章,但那里的答案(MyModel.where("created_at < ?", 2.days.ago)(抛出了一些错误。

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

@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

基本上,我需要当前用户的plan,该week_starting值最接近Date.today但仍然在过去。

检查这个

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

这对你有用吗?

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

不知道你为什么有week_starting,那是什么。 但是要获得过去的最新记录,就足够了

最新更新