计入视图问题?

时间:2013-10-28 16:42:57

标签: ruby-on-rails ruby ruby-on-rails-2

我正在使用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

请有人帮我这个吗?

1 个答案:

答案 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 %>