使用数据库中的总计数显示单个名称条目

时间:2017-02-16 22:18:59

标签: ruby-on-rails ruby

我从CSV文件上传了一堆条目,需要按公司显示条目数。我能够在HTML中的JSON对象中显示信息,但它显示数据库中的每个条目,而不是为每个公司显示一次。我需要它看起来像这样:

ABC Dirtworks 4
Dirt Diggler 2
John Doe Mining 2
Spider Crawlers 2
Standard Tractor and Machines 3

目前显示的内容更像是这样:

ABC DirtWorks   {"ABC DirtWorks"=>4, "Dirt Diggler"=>2, "John Doe Mining"=>2, "Spider Crawlers"=>2, "Standard Tractor and Machines"=>3}
John Doe Mining {"ABC DirtWorks"=>4, "Dirt Diggler"=>2, "John Doe Mining"=>2, "Spider Crawlers"=>2, "Standard Tractor and Machines"=>3}
ABC DirtWorks   {"ABC DirtWorks"=>4, "Dirt Diggler"=>2, "John Doe Mining"=>2, "Spider Crawlers"=>2, "Standard Tractor and Machines"=>3}
ABC DirtWorks   {"ABC DirtWorks"=>4, "Dirt Diggler"=>2, "John Doe Mining"=>2, "Spider Crawlers"=>2, "Standard Tractor and Machines"=>3}
John Doe Mining {"ABC DirtWorks"=>4, "Dirt Diggler"=>2, "John Doe Mining"=>2, "Spider Crawlers"=>2, "Standard Tractor and Machines"=>3}

等等,等等。

这是我的模特:

class Vehicle < ApplicationRecord
  require 'csv'

  def self.import(file)
    CSV.foreach(file.path, headers:true) do |row|
      Vehicle.create! row.to_hash
    end
  end

  def count
    Vehicle.group(:company_name).count
  end
end

这是我的控制者:

class VehiclesController < ApplicationController
  def index
    @vehicles = Vehicle.all
  end

  def import
    Vehicle.import(params[:file])
    redirect_to '/', notice: 'Your files were successfully uploaded!'
  end
end

这是我的观点,因为它与本节有关:

  <tbody>
    <% @vehicles.each do |vehicle| %>
    <tr>
      <td><%= vehicle.company_name %></td>
      <td><%= vehicle.count %></td>
    </tr>
    <% end %>
  </tbody>

2 个答案:

答案 0 :(得分:0)

您的问题在于此代码:

def count
  Vehicle.group(:company_name).count
end

这就是说&#34;计算按公司名称分组的所有车辆&#34;但是你在这里使用它:

  <td><%= vehicle.count %></td>

你似乎想要的是&#34;对于这个车辆的实例,计算有多少车辆&#34;

即代码没有按照你想要的方式运行,因为它们正在做两件不同的事情。

所以...你想要做的不是对车辆的每个实例进行呼叫计数(你可能想要将计数方法重命名为更具描述性且不容易被误解的东西)对于&#34;正常&#34;计数)例如尝试类似:

class Vehicle < ApplicationRecord
  def self.company_counts
    Vehicle.group(:company_name).count
  end
end

class VehiclesController < ApplicationController
  def index
    @vehicles = Vehicle.all
    @counts = Vehicle.company_counts
  end
end

<% @vehicles.each do |vehicle| %>
  <tr>
    <td><%= vehicle.company_name %></td>
    <td><%= @counts[vehicle.company_name] %></td>
  </tr>
<% end %>

答案 1 :(得分:0)

Taryn的答案是正确的,但我会选择一个查询:

class VehiclesController < ApplicationController
  def index
    @counts_by_company = Vehicle.company_counts
  end
end

<% @counts_by_company.each do |company, count| %>
  <tr>
    <td><%= company %></td>
    <td><%= count %></td>
  </tr>
<% end %>