Ruby 在 Rails - 计算脚手架上的条目
Ruby on Rails - Count Entries on Scaffold
在一个简单的 Ruby on Rails 应用程序中,我有一个名为 "Proposals" 的脚手架,其中一列是一个名为 "creationyear" 的字符串。我正在尝试计算每年在加载索引页面时创建了多少提案,执行以下操作(在 "proposals_controller.rb" 文件中):
def index
@proposals = Proposal.all
@count2015 = Proposal.count(:all, :conditions => "creationyear = 2015")
@count2016 = Proposal.count(:all, :conditions => "creationyear = 2016")
end
不知何故它不起作用,因为它让我返回了两个变量脚手架上的条目总数。
有谁知道如何解决这个问题?我正在使用 Rails v4.2.6.
谢谢!
@count2015 = Proposal.where(creationyear: '2015').count
如果creationyear
是一个字符串,否则没有引号。
为什么不按年份对提案进行分组?
@proposals = Proposal.group(:creationyear).count
或
@proposals = Proposal.group('creationyear').select('*, COUNT(*) as quantity')
这会将每年发生的查询减少到一个查询。
此处的其他答案很好,但值得提供一些背景知识。
count
在 Active Record 中的使用方式自 Rails 的早期版本以来发生了变化。您可能从 Rails 3 或更早版本中找到了一个示例,其中可以按照您尝试的方式指定条件。
在 Rails 的较新版本中,可以使用列名调用 count
,例如
Person.count(:email) # number of person records that have an email address
但在其他情况下通过首先创建作用域来使用,例如通过使用 where
,然后在其上调用 count
:
Proposal.where(creationyear: '2015').count
在一个简单的 Ruby on Rails 应用程序中,我有一个名为 "Proposals" 的脚手架,其中一列是一个名为 "creationyear" 的字符串。我正在尝试计算每年在加载索引页面时创建了多少提案,执行以下操作(在 "proposals_controller.rb" 文件中):
def index
@proposals = Proposal.all
@count2015 = Proposal.count(:all, :conditions => "creationyear = 2015")
@count2016 = Proposal.count(:all, :conditions => "creationyear = 2016")
end
不知何故它不起作用,因为它让我返回了两个变量脚手架上的条目总数。
有谁知道如何解决这个问题?我正在使用 Rails v4.2.6.
谢谢!
@count2015 = Proposal.where(creationyear: '2015').count
如果creationyear
是一个字符串,否则没有引号。
为什么不按年份对提案进行分组?
@proposals = Proposal.group(:creationyear).count
或
@proposals = Proposal.group('creationyear').select('*, COUNT(*) as quantity')
这会将每年发生的查询减少到一个查询。
此处的其他答案很好,但值得提供一些背景知识。
count
在 Active Record 中的使用方式自 Rails 的早期版本以来发生了变化。您可能从 Rails 3 或更早版本中找到了一个示例,其中可以按照您尝试的方式指定条件。
在 Rails 的较新版本中,可以使用列名调用 count
,例如
Person.count(:email) # number of person records that have an email address
但在其他情况下通过首先创建作用域来使用,例如通过使用 where
,然后在其上调用 count
:
Proposal.where(creationyear: '2015').count