= #{Time.now - 5.days}")-6ren"> = #{Time.now - 5.days}")-这一直困扰着我一段时间... 如何字符串插值 datetime在 Rails ActiveRecord 查询中? # Works, but supeh ugleh: Model.where("crea-6ren">
gpt4 book ai didi

ruby-on-rails - 我该怎么做呢? Model.where ("created_at >= #{Time.now - 5.days}")

转载 作者:行者123 更新时间:2023-12-03 13:02:17 26 4
gpt4 key购买 nike

这一直困扰着我一段时间...

如何字符串插值 datetime在 Rails ActiveRecord 查询中?

# Works, but supeh ugleh:
Model.where("created_at >= ?", Time.now - 5.days)

# How do I do this?
Model.where("created_at >= #{Time.now - 5.days}")
# As is, it produces the following error message:
# ActiveRecord::StatementInvalid: PG::Error: ERROR: syntax error at or near ...

我关心的原因是代码可读性:
# I like this better:
Model.where("created_at >= #{Time.now - 5.days} OR" + \
"updated_at >= #{Time.now - 3.days}")

# than this:
Model.where("created_at >= ? OR updated_at >= ?", Time.now - 5.days, Time.now - 3.days)

最佳答案

老问题,但我最喜欢的方法是:

Model.where(created_at: 5.days.ago..Time.current)

更漂亮,更具可读性。

另外, Rails 3.2 introduced一些 Active Support 辅助方法来获取一些常用范围, Time#all_day , Time#all_week , Time#all_quarterTime#all_year ,因此您可以例如执行以下操作:
Model.where(created_at: Time.current.all_week)

关于ruby-on-rails - 我该怎么做呢? Model.where ("created_at >= #{Time.now - 5.days}"),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9748082/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com