gpt4 book ai didi

ruby-on-rails - 如何对数组中的值求和?

转载 作者:太空宇宙 更新时间:2023-11-03 17:33:24 25 4
gpt4 key购买 nike

我使用 Rails 开发了一个应用程序,我在对每一行求和时遇到了问题,但我遇到了错误。

这是我的表格:

|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

这是我的 Controller :“app/controllers/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

这是我的索引 View :“app/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

我正在尝试做这个例子:

enter image description here

有人可以帮助我吗?

怎么了?

将接受各种帮助。

最佳答案

你可以这样做:

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>

关于ruby-on-rails - 如何对数组中的值求和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25999497/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com