Rails中每个相关记录的Sum属性?

时间:2012-11-24 11:23:56

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

在我的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 animal。动物有很多主张并且已被排除在外。

因此,用户创建一个声明,该声明会在每个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

因此,每个条件的值总结在属于当前动物的所有声明中。

这可能吗?

1 个答案:

答案 0 :(得分:2)

如果您当前的动物被称为@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) %>

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

相关问题