【问题标题】:how to write a scope containing an OR for greaterThan & LessThan - Rails如何编写包含大于和小于 OR 的范围 - Rails
【发布时间】:2018-07-21 13:19:29
【问题描述】:

如何为结束日期小于当前日期或等于 && 大于当前日期的事件编写范围?

我尝试了以下方法,但它似乎不起作用:

事件.rb

scope :events_with_endTime_greaterOrLess_than_currentDate, -> {where(['end_date > ? OR end_date < ?', Date.current])}

架构

create_table "events", force: :cascade do |t|
    t.string   "name"
    t.datetime "start_date"
    t.datetime "end_date"
    t.text     "description"
    t.text     "address"
    t.integer  "user_id"
    t.boolean  "approve"
    t.boolean  "close"
    t.index ["slug"], name: "index_events_on_slug", unique: true
  end

尝试显示 enddate 小于 currentDate [但不等于当前日期]的事件

【问题讨论】:

  • 这是所有事件吗?你能给出示例表和预期结果吗?

标签: ruby-on-rails scope


【解决方案1】:

由于end_date 是一个日期时间,数据库比较将以该精度级别应用——因此您当前的代码只是避免设置正好为午夜的条目。

为避免这种情况,您可以使用beginning_of_dayend_of_day 方法为您的查询获取更合适的时间:

scope :events_not_today, -> {
  where('end_date > ? OR end_date < ?', Date.current.end_of_day, Date.current.beginning_of_day)
}

或者,对于更短的拼写:

scope :events_not_today, -> { where.not(end_date: Date.current.all_day) }

【讨论】:

    猜你喜欢
    • 2016-04-14
    • 1970-01-01
    • 2014-11-27
    • 2017-05-02
    • 1970-01-01
    • 1970-01-01
    • 2011-06-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多