Pregunta

I'm working with Ruby on Rails, and wrote an application to count results in my view, but it is not working.

Here are my tables:

|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

I want this:

 |policy_id|   |count_num|
    1               2
    2               3
    3               1       

Here is my controller:

class PolicyManagement < ApplicationController
  def generate_print_cupons
     @search = Debt.find(:all,:group=>:policy_id)
  end
end

Here is my model:

class Debt < ActiveRecord::Base
   belongs_to :policy
end

class Policy < ActiveRecord::Base
   has_many :debts
end

This is my view:

  <% @search.each do |debt| %>
     <%= debt.policy.num %>       
  <% end %>

I'm trying to count debt.policy.num.

I tried:

  <% @search.each do |debt| %>
     <%= debt.count(:num) %>       
  <% end %>
  undefined method `count' for #<ActiveRecord::Associations::BelongsToAssociation:0x7fb5afefd050>

And also I tried:

  <% @search.each do |debt| %>
     <%= debt.num.count %>       
  <% end %>

  undefined method `count' for 41:Fixnum

Please somebody can help me with this?

¿Fue útil?

Solución

If the goal is to count the number of debts for each policy, why not perform the count from Policy rather than Debt?

Your controller would change to something like:

class PolicyManagement < ApplicationController
  def generate_print_cupons
     @search = Policy.all
  end
end

Then your view could be as trivial as:

<% @search.each do |policy| %>
   <%= policy.debts.size %>       
<% end %>
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top