Ruby on rails Rails:根据不同的字段类型计算多个结果的总和

Ruby on rails Rails:根据不同的字段类型计算多个结果的总和,ruby-on-rails,ruby,ruby-on-rails-4,Ruby On Rails,Ruby,Ruby On Rails 4,我的用户有许多与他们相关的投资模型。我需要做的是计算他们所有贡献的总和:每月一列关于投资模型的内容,我将在下面讨论 在我的控制器中,我有: #get Investment types that are Roth IRAs, Traditional IRAs, etc. @getira = Investment.where(user_id: current_user, investmenttype: ["Roth IRA","Traditional IRA","Other"]) 通

我的用户有许多与他们相关的投资模型。我需要做的是计算他们所有贡献的总和:每月一列关于投资模型的内容,我将在下面讨论

在我的控制器中,我有:

   #get Investment types that are Roth IRAs, Traditional IRAs, etc.
    @getira = Investment.where(user_id: current_user, investmenttype: ["Roth IRA","Traditional IRA","Other"])
通常,我会在该查询中添加.sum:contributions。然而,并非所有捐款都是平等的

投资还有一个:contributionfrequency字段,这是一个字符串,用户可以在其中选择每月、每季度或每年

因此,我在同一控制器中添加了以下内容:

当我执行此操作时,会出现以下错误:

找不到没有ID的投资


我不确定是否进行了正确的查询,或者是否在此处输入了正确的字段

您一定收到了错误,无法在下一行中找到没有ID的投资

 investment = @getira.find(params[:contributionfrequency])
这仅仅意味着params[:contributionfrequency]为零,即您没有在params中传递键:contributionfrequency

根据与OP的聊天会话,删除了参数[:contributionfrequency],并使用了直接查询:

@contribution_quarterly = Investment.where(user_id: current_user, investmenttype: ["Roth IRA","Traditional IRA","Other"], contributionfrequency: ["Quarterly"]).sum(:contribution) 
@contribution_monthly = Investment.where(user_id: current_user, investmenttype: ["Roth IRA","Traditional IRA","Other"], contributionfrequency: ["Monthly"]).sum(:contribution) 
@contribution_annually = Investment.where(user_id: current_user, investmenttype: ["Roth IRA","Traditional IRA","Other"], contributionfrequency: ["Annually"]).sum(:contribution) 

如何在参数中传递键:contributionfrequency?
@contribution_quarterly = Investment.where(user_id: current_user, investmenttype: ["Roth IRA","Traditional IRA","Other"], contributionfrequency: ["Quarterly"]).sum(:contribution) 
@contribution_monthly = Investment.where(user_id: current_user, investmenttype: ["Roth IRA","Traditional IRA","Other"], contributionfrequency: ["Monthly"]).sum(:contribution) 
@contribution_annually = Investment.where(user_id: current_user, investmenttype: ["Roth IRA","Traditional IRA","Other"], contributionfrequency: ["Annually"]).sum(:contribution)