【问题标题】:Sum attributes of each related record in Rails?Rails中每个相关记录的属性总和?
【发布时间】:2012-11-24 11:23:56
【问题描述】:

在我的 Rails 3 中,我有以下模型:

Animal
Claim
Exclusion

模型关系如下:

Animal has_one exclusion
Animal has_many claims
Claim has_one Animal
Exclusion belongs_to Animal

在排除表中,我有以下列:

animal_id, con1, con2, con3, con4, con5

在索赔表中,我有以下列:

animal_id, con1, con2, con3, con4, con5, description, date

排除has_one 动物和声明has_one 动物。动物 has_many 声明和 has_one 排除。

因此,用户创建了一个声明,该声明在每个 con* 列旁边添加了一个值。我如何(在“动物”视图中)汇总每种情况的索赔总额?

例如;在我的动物视图中:

Condition 1 = 10.00
Condition 2 = 20.00
Condition 3 = 0.00
Condition 4 = 200.00
Condition 5 = 232.22

上述条件旁边的值取自以下声明:

ID, con1, con2, con3, con4, con5, animal_id
-------------------------------------------
1,  5.00, 10.00, 0.00, 100.00, 200.00, 123
2,  5.00, 10.00, 0.00, 100.00, 32.22, 123

因此,每个条件的值都会在属于当前动物的所有声明中相加。

这可能吗?

【问题讨论】:

  • 吹毛求疵,但是:An exclusion has_one animal and a claim has_one animal. 这应该是An exclusion belongs_to one animal and a claim belongs_to one animal.,对吧?同样在您的模型关系列表中,声明应为:Claim belongs_to Animal

标签: ruby-on-rails-3 model sum relationship


【解决方案1】:

如果您当前的动物被称为@animal,那么您可以使用sum 方法将所有声明中特定条件的值相加:

con1_sum = @animal.claims.sum(:con1)

在您看来,您可以这样做:

Condition 1 = <%= @animal.claims.sum(:con1) %>
Condition 2 = <%= @animal.claims.sum(:con2) %>
Condition 3 = <%= @animal.claims.sum(:con3) %>
Condition 4 = <%= @animal.claims.sum(:con4) %>
Condition 5 = <%= @animal.claims.sum(:con5) %>

在控制器动作中而不是直接在视图中计算这些可能更有意义,但无论如何你明白了。

【讨论】:

  • +1 因为很容易忘记 ActiveRecord::Calculations(包括我自己 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多