[英]What is the best way to reuse a scope in Rails?
我对重用或编写新的 scope 感到困惑。例如,
我的一种方法将返回未来订阅或当前订阅或 sidekiq 创建的订阅。
因为范围看起来像:
scope :current_subscription, lambda {
where('(? between from_date and to_date) and (? between from_time and to_time)', Time.now, Time.now)
}
scope :sidekiq_created_subscription, lambda {
where.not(id: current_subscription).where("(meta->'special_sub_enqueued_at') is not null")
}
scope :future_subscription, lambda {
where.not(id: current_subscription).where("(meta->'special_sub_enqueued_at') is null")
}
所以这些以不同的方法用于不同的目的,所以对我来说,我尝试的是检查特定的帐户记录是否属于三个订阅中的哪一个。
所以我试过:
def find_account_status
accounts = User.accounts
name = 'future' if accounts.future_subscription.where(id: @account.id).any?
name = 'ongoing' if accounts.current_subscription.where(id: @account.id).any?
name = 'sidekiq' if accounts.sidekiq_enqued_subscription.where(id: @account.id).any?
return name
end
所以我的疑问是,这样使用是否是一种好方法,因为在这里我们将根据特定订阅获取记录,然后我们检查我们的订阅是否存在。
谁能提出更好的方法来实现这一目标?
首先,你在这里使用范围。
#find_account_status
方法将执行大约 4 个查询,如下所示:
Q1 => accounts = User.accounts
Q2 => accounts.future_subscription
Q3 => accounts.current_subscription
Q4 => accounts.sidekiq_enqued_subscription
您的功能可以通过简单地使用@account
object 来实现,它已经存在于 memory 中,如下所示:
def current_subscription?
# Here I think just from_time and to_time will do the work
# but I've added from_date and to_date as well based on the logic in the question
Time.now.between?(from_date, to_date) && Time.now.between?(from_time, to_time)
end
def future_subscription?
!current_subscription? && meta["special_sub_enqueued_at"].blank?
end
def sidekiq_future_subscription?
!current_subscription? && meta["special_sub_enqueued_at"].present?
end
#find_account_status
可以重构如下: def find_account_status
if @account.current_subscription?
'ongoing'
elsif @account.future_subscription?
'future'
elsif @account.sidekiq_future_subscription?
'sidekiq'
end
end
此外,据我了解代码,我认为您还应该处理 from_date 和 to_date 是过去日期的情况,因为如果不处理,可以根据字段 meta["special_sub_enqueued_at"] 设置状态这可以提供不正确的状态。
例如,假设帐户中的from_date
设置为 2021 年 12 月 31 日,并且meta["special_sub_enqueued_at"]
为 false 或 nil。
在这种情况下, #current_subscription?
将返回 false 但#future_subscription?
将返回 true,这是不正确的,因此应该处理过去日期的情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.