Ruby on rails 简单求和在Rails中不起作用

Ruby on rails 简单求和在Rails中不起作用,ruby-on-rails,Ruby On Rails,我想对列求和。 在我的控制器中 def index @performance_reports = PerformanceReport.all end 我的错误: undefined method `+' for #<PerformanceReport:0x4a55690> 74: <td><%= @performance_reports.sum(:clicks)%><

我想对列求和。 在我的控制器中

         def index
          @performance_reports = PerformanceReport.all
         end
我的错误:

       undefined method `+' for #<PerformanceReport:0x4a55690>
74:         <td><%=  @performance_reports.sum(:clicks)%></td>
的未定义方法“+”#
74:         

有什么问题吗?

sum
是一种ActiveRecord方法,因此您不能在已选择的对象上使用它!ypu可以做什么:

PerformanceReport.sum(:clicks)

因为这样数据库就被查询了

sum
是一种ActiveRecord方法,因此您不能在已选择的对象上使用它!ypu可以做什么:

PerformanceReport.sum(:clicks)
因为这样数据库就被查询了

试试看

 @performance_reports = PerformanceReport.select('*')
在视图中

<td><%=  @performance_reports.sum(:clicks)%></td>

基本上
PerformanceReport.all
将加载整个表并返回
PerformanceReport
Array
,您不能在Array上链接查询

PerformanceReport.select('*')
将返回
ActiveRecord::Relation
,您可以在Relation上链接任何AR方法

我建议您阅读rails延迟加载策略和

很棒的Rails

试试看

 @performance_reports = PerformanceReport.select('*')
在视图中

<td><%=  @performance_reports.sum(:clicks)%></td>

基本上
PerformanceReport.all
将加载整个表并返回
PerformanceReport
Array
,您不能在Array上链接查询

PerformanceReport.select('*')
将返回
ActiveRecord::Relation
,您可以在Relation上链接任何AR方法

我建议您阅读rails延迟加载策略和

棒极了的铁轨