【问题标题】:How to find out the number of records in a table? [closed]如何找出表中的记录数? [关闭]
【发布时间】:2020-01-06 06:56:30
【问题描述】:

我有一份脚手架帮助申请。有一个状态字段。每个请求可以有 3 个状态(pending、in_progress、finished),通过枚举实现。有必要编写方法来计算每个状态的请求数。例如,方法 A 计算状态为 0(待处理)的帮助程序请求总数。我知道这没有什么复杂的,但我无法理解并且可以使用一些帮助。

【问题讨论】:

  • 我不知道你甚至需要方法。使用枚举为状态提供了一个范围,因此您可以调用,例如,YourModel.in_progress.count。这对我来说似乎很惯用,并且节省了将计数转换为单独方法所需的九行代码。

标签: ruby-on-rails ruby


【解决方案1】:

在你的模型上应该是这样的:

def self.pending_count
 where(status: 0).count
end


def self.in_progress_count
 where(status: 1).count
end

def self.finished_count
 where(status: 2).count
end

然后您可以在任何需要的地方调用Model.pending_count(或其他方法)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-02
    • 1970-01-01
    • 2020-12-21
    • 2013-10-19
    • 2013-12-20
    • 1970-01-01
    • 2018-01-17
    • 1970-01-01
    相关资源
    最近更新 更多