0

在我的 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 animal 和声明 has_one animal。动物 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

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

这可能吗?

4

1 回答 1

3

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

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

于 2012-11-24T12:18:16.930 回答