0

In my Rails 3 I have the following models:

Animal
Claim
Exclusion

The model relations are as follows:

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

In the exclusions table I have the following columns:

animal_id, con1, con2, con3, con4, con5

In the claim table I have the following columns:

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

An exclusion has_one animal and a claim has_one animal. Animal has_many claims and has_one exclusion.

So, the user creates a claim which adds a value alongside each of the con* columns. How can I (in the Animal view) sum the total claimed for each condition?

For example; in my Animal view:

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

The values alongside the above conditions are taken from the following claims:

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

So the values of each condition is summed up across all claims belonging to the current animal.

Is this possible?

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 に答える