2014-09-23 4 views
1

레일을 사용하는 응용 프로그램을 만들었는데 각 행에서 총계를 계산하는 데 문제가 있지만 오류가 발생합니다. 여기배열에서 값을 어떻게 합계 할 수 있습니까?

내 테이블 : 여기

|policies| 
    |id| |num_policy| 
    1  1000 
    2  1001 
    3  1002 
    4  1003 

|policy_vehicles|  
    |id| |policy_id| |vehicle_id| 
    1   1   1 
    2   1   2 
    3   2   1 
    4   2   3 
    5   3   1 
    6   4   4 
    7   4   2 

|vehicles| 
    |id| |name|  |amount| 
    1 VEHICLE1  8000 
    2 VEHICLE2  8001 
    3 VEHICLE3  8002 
    4 VEHICLE4  8003 

내 컨트롤러 : "응용 프로그램/컨트롤러/policy_controller.rb"

모델 :

여기
class PolicyVehicle < ActiveRecord::Base 
    belongs_to :vehicle 
    belongs_to :policy 
end 

class Vehicle < ActiveRecord::Base 
    belongs_to :policy 
    has_many :policy_vehicles 
end 

class Vehicle < ActiveRecord::Base 
    has_many :policy_vehicles 
end 

내 인덱스이다 : "응용 프로그램 /views/policy/index.html.erb "

<table border="1"> 
    <tr> 
    <td>POLICY ID</td> 
    <td>NUM POLICY</td> 
    </tr> 

<% @policies.each do |policy| %> 
    <tr> 
    <td><%= policy.id %></td> 
    <td><%= policy.num_policy %></td> 
    </tr> 

    <% policy.policy_vehicles.each do |policy_vehicle| %> 
    <tr> 
    <td></td> 
    <td><%= policy_vehicle.vehicle.name %></td> 
    <td><%= policy_vehicle.vehicle.amount %></td> 
    </tr> 
    <% end %> 

    <tr> 
    <td></td> 
    <td>TOTAL</td> 
    <td><%= policy.policy_vehicles.vehicles.sum(:amount) %></td> 
    </tr> 

<% end %> 
</table> 

내가하려고하면 :

<%= policy.policy_vehicles.vehicles.sum(:amount) %> 
##### GET THIS ERROR ##### 
undefined method `vehicles' for #<Class:0x7ff4293ac3f0> 

내가하려고하면 :

<%= policy.policy_vehicles.vehicle.sum(:amount) %> 
##### GET THIS ERROR ##### 
undefined method `vehicle' for #<Class:0x7ff42ae95a90> 

내가하려고하면 :

<%= policy.policy_vehicles.vehicles.collect(&:amount).sum %> 
##### GET THIS ERROR ##### 
undefined method `vehicles' for #<Class:0x7ff429337410> 

내가하려고하면 :

<% policy.policy_vehicles.each do |policy_vehicle|%> 
    <%= policy_vehicle.vehicle.sum(:amount) 
<% end %> 
##### GET THIS ERROR ##### 
undefined method `sum' for #<ActiveRecord::Associations::BelongsToAssociation:0x7ff4295dbd60> 

마지막으로 나는 시도했다 :

<% policy.policy_vehicles.each do |policy_vehicle|%> 
    <%= policy_vehicle.vehicle.amount.sum 
<% end %> 
##### GET THIS ERROR ##### 
undefined method `sum' for 8000:Fixnum 
I이 예 할 노력하고있어

:

enter image description here

누군가가 나를 도울 수하세요?

무엇이 잘못 되었나요?

모든 종류의 도움이 받아 들여집니다.

답변

5

당신은 할 수 : 다음

class Policy < ActiveRecord::Base 
    has_many :policy_vehicles 
    has_many :vehicles, through: policy_vehicles 
end 

과 :

<tr> 
    <td></td> 
    <td>TOTAL</td> 
    <td><%= policy.vehicles.sum(:amount) %></td> 
</tr> 
+0

환상적인 일을 훌륭한 대답을, 또한 내가 좋은 내용을 작성하고 좋은 질문으로 설명 통지 : D를 –

관련 문제