我正在使用Ruby on Rails,并在我的视图中编写了一个计算结果的应用程序,但它没有用。
以下是我的表格:
|policies|
|id| |num|
1 1234
2 5678
3 1551
|debts|
|id| |policy_id|
1 1
2 1
3 2
4 2
5 3
6 2
我想要这个:
|policy_id| |count_num|
1 2
2 3
3 1
这是我的控制器:
class PolicyManagement < ApplicationController
def generate_print_cupons
@search = Debt.find(:all,:group=>:policy_id)
end
end
这是我的模特:
class Debt < ActiveRecord::Base
belongs_to :policy
end
class Policy < ActiveRecord::Base
has_many :debts
end
这是我的观点:
<% @search.each do |debt| %>
<%= debt.policy.num %>
<% end %>
我正在尝试计算debt.policy.num
。
我试过了:
<% @search.each do |debt| %>
<%= debt.count(:num) %>
<% end %>
undefined method `count' for #<ActiveRecord::Associations::BelongsToAssociation:0x7fb5afefd050>
我也尝试过:
<% @search.each do |debt| %>
<%= debt.num.count %>
<% end %>
undefined method `count' for 41:Fixnum
请有人帮我这个吗?
答案 0 :(得分:2)
如果目标是为每个debts
计算policy
的数量,为什么不从Policy
而不是Debt
执行计数?
您的控制器将更改为:
class PolicyManagement < ApplicationController
def generate_print_cupons
@search = Policy.all
end
end
然后你的观点可能像以下一样微不足道:
<% @search.each do |policy| %>
<%= policy.debts.size %>
<% end %>