我用的是日历Ruby ,要求event.start_time记录为"2023-11-07".

我需要找到这个月和上个月的所有事件在start_time的基础上,其中event.rained_out == false

event.start_time[0,4].to_i == Time.now.year && event.start_time[5,2] == Time.now.month || event.start_time[5,2] == Time.now.month && event.rained_out== false

我不知道如何使用active record查询来获得这一点.

Event.where("start_time[5,2].to_i = ?", Time.now.month)

是语法错误吗

推荐答案

我知道您的数据库中的start_time列是字符串类型,并且您希望查找日期以标识上个月或当前月份的特定字符串开头的所有行.

我将首先为这些格式化的日期字符串前缀创建一个范围,如下所示:

date_prefixes = [1.month.ago, 1.month.since].map { |time| time.strftime('%Y-%m') }
#=> ["2023-10", "2023-12"]
prefixes_range = Range.new(*date_prefixes, exclude_end = true)
#=> "2023-10"..."2023-12"

然后,您可以将该范围传递给ActiveRecord查询,以查找该范围中包含的所有字符串.这将是所有以2023-102023-11开头的开始日期,但不是以2023-12开头,因为exclude_end = true.

Event.where(start_time: prefix_range)

这基本上转换为如下所示的SQL查询:

start_date >= '2023-10' AND start_date < '2023-12'

把所有东西放在一个范围内:

# in app/models/event.rb
scope :started_this_or_previous_month, -> {
  where(
    start_date: Range.new(
      *[1.month.ago, 1.month.since].map { |t| t.strftime('%Y-%m') }, true
    )
  )
}

# use scope like this:
Event.started_this_or_previous_month.where(rained_out: false)

顺便说一句.即使您使用的gem要求start_date是一个字符串.您可能希望考虑向表中添加一列,如start_atstart_on,类型为DATETIME或DATE,并使这两列保持同步.这将使数据库查询变得更加容易.

Ruby-on-rails相关问答推荐

通过激励控制器正确更新Turbo帧信源

关于关联 has_many 的多级/三重嵌套形式

URL 中的 Rails slugs - 使用 Active Record Model Post 的 Title 属性而不是 ID

ViewModel 和 Controller 有什么区别?

如何在 IRB/Rails 控制台中 suppress 返回值的输出?

如何在 Rails 3 中使用 Capybara 单击具有相同文本的第二个链接?

ArgumentError:您需要使用 :if 提供至少一个验证

循环大量记录时 Ruby on Rails 内存泄漏; find_each 没有帮助

有没有办法在模型而不是视图中使用复数()?

fields_for 表单构建器对象为零

带有 master.key 的 Rails 5.2 - Heroku 部署

Rails 5:无法从参数中检索哈希值

Groovy/Grails :: Ruby/Rails :: 2011 框架状态

表单中的第一个参数不能包含 nil 或为空 - Rails 4

rails 单数资源还是复数?

在 rails 3 中批量插入

将 Rails 服务器绑定到 0.0.0.0 能给你带来什么?

:javascript haml 标签中的内联Ruby ?

反编译开发assets资源 管道

Rails:每个环境的初始化程序?