gpt4 book ai didi

ruby-on-rails - "one, other or both"案例的更好解决方案

转载 作者:数据小太阳 更新时间:2023-10-29 07:40:31 24 4
gpt4 key购买 nike

我正在检查一些代码,并且出现了类似于以下内容的内容:

def between_dates(date_1, date_2)
if date_1 && date_2
conditions "created_at >= date_1 AND created_at <= date_2"
elseif date_1
conditions "created_at >= date_1"
elseif date_2
conditions "created_at <= date_2"
end
end

它看起来是一种可以改进的代码,但我找不到更优雅的解决方案来处理这种琐碎而常见的条件语句。

当我们必须为一个、另一个或两者返回一个值时,我正在为这个问题寻找更好的答案。

最佳答案

Rails 允许您动态构建查询。这是一个使用 scopes 的示例和一个类方法。由于范围总是返回一个 ActiveRecord::Relation 对象(即使该 block 返回 nil),它们是可链接的:

class Event < ApplicationRecord
scope :created_before, -> (date) { where('created_at <= ?', date) if date }
scope :created_after, -> (date) { where('created_at >= ?', date) if date }

def self.created_between(date_1, date_2)
created_after(date_1).created_before(date_2)
end
end

示例用法:

Event.created_between(nil, Date.today)
# SELECT `events`.* FROM `events` WHERE (created_at <= '2018-05-15')

Event.created_between(Date.yesterday, nil)
# SELECT `events`.* FROM `events` WHERE (created_at >= '2018-05-14')

Event.created_between(Date.yesterday, Date.today)
# SELECT `events`.* FROM `events` WHERE (created_at >= '2018-05-14') AND (created_at <= '2018-05-15')

关于ruby-on-rails - "one, other or both"案例的更好解决方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50344728/

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