在一个简单的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。
谢谢!
答案 0 :(得分:1)
这里的其他答案都很好,但值得提供一些背景知识。
自早期版本的Rails以来,Active Record中使用count
的方式已发生变化。您可以在Rails 3或更早版本中找到一个示例,其中可以按照您尝试的方式指定条件。
在更新版本的Rails中,可以使用列名称调用count
,例如
Person.count(:email) # number of person records that have an email address
但在其他情况下通过首先创建范围来使用,例如使用where
,然后在其上调用count
:
Proposal.where(creationyear: '2015').count
答案 1 :(得分:0)
@count2015 = Proposal.where(creationyear: '2015').count
如果creationyear
是字符串,则不带引号。
答案 2 :(得分:0)
为什么不按年度对提案进行分组?
@proposals = Proposal.group(:creationyear).count
或
@proposals = Proposal.group('creationyear').select('*, COUNT(*) as quantity')
这会将每年发生的查询减少到一个查询。