我怎样才能在我的视图中计算一列?

时间:2021-09-17 00:16:27

I did an app to show a column from another table but i want to know how to count the results instead of showing information

我做了一个应用程序来显示另一个表中的列,但我想知道如何计算结果而不是显示信息

Here my tables

在这里我的表

|policies|
 |id|  |num_policy|
   1       11111
   2       22222

|insurances|
 |id|  |id_policy| |net_insurance|
  1        1          33333
  2        1          44444  
  3        2          55555
  4        2          66666  

|insurance_financing|       
  |id| |id_ensurance| |number|
   1       1            1544
   2       2             858
   3       3            8484  
   4       4             848

I'm trying to do

我正在尝试做

|num_policy|    |count| 
     11111       2
     22222       2

This is my controller

这是我的控制器

class PolicyController < ApplicationController
    def generate_print
      @policies= Policy.find(:all)
    end
end

This is my model

这是我的模特

class Policy < ActiveRecord::Base
  has_many :insurances
end

class Insurance < ActiveRecord::Base
  belongs_to :policy
  has_many :insurance_financing_details
end

class InsuranceFinancingDetail < ActiveRecord::Base
  belongs_to :insurance
end        

This is my view

这是我的观点

 <% @policies.each do |p| %>
    <%= p.num_policy   %>

    <%  p.insurances.each do |insurance| %>
       <% insurance.insurance_financing_details.each do |detail| %>
          <%= detail.number %>
       <% end %>
    <% end %>
 <% end %>

Please somebody can help me with this problem

请有人帮我解决这个问题

I will really appreciate help

我真的很感激帮助

1 个解决方案

#1


1  

Policies.joins(:insurances).group("policies.id").count will give you a hash where the key is the policies.id and the value is the count of the insurances for each policy.

Policies.joins(:insurances).group(“policies.id”)。count将为您提供一个哈希,其中键是policies.id,值是每个策略的保险计数。

NOTE: if a policy does not have any insurances, it will not be included in the result.

注意:如果保单没有任何保险,则不会包含在结果中。

#1


1  

Policies.joins(:insurances).group("policies.id").count will give you a hash where the key is the policies.id and the value is the count of the insurances for each policy.

Policies.joins(:insurances).group(“policies.id”)。count将为您提供一个哈希,其中键是policies.id,值是每个策略的保险计数。

NOTE: if a policy does not have any insurances, it will not be included in the result.

注意:如果保单没有任何保险,则不会包含在结果中。