【问题标题】:rails, can't display postgres array count results in viewrails,无法在视图中显示 postgres 数组计数结果
【发布时间】:2015-05-06 10:42:58
【问题描述】:

Rails 4.2.1 Ruby 2.0.0

我想在 rails 视图中将 postgres 数组计数查询的结果显示为一个简单的表。该表应有 2 列;部署和计数。

我能够使用以下 SQL 成功查询 postgres

select unnest(deployed), count(deployed) from current_customer_profiles group by current_customer_profiles.deployed;

postgres 查询的结果是

deployed | count

on prem  | 4

saas     | 2

我曾尝试在 rails 中使用 select_rowsfind_by_sql

@deployment = CurrentCustomerProfile.connection.select_rows('select unnest(deployed) as deployed, count(deployed) as count from current_customer_profiles group by current_customer_profiles.deployed')

@deployment = CurrentCustomerProfile.find_by_sql(%q{select unnest(deployed) as deployed, count(deployed) as count from current_customer_profiles group by current_customer_profiles.deployed})

我尝试了许多不同的方法来让数据在 rails 视图中显示为一个简单的表格。

我遇到的问题是:

  1. 字符串(部署列)在视图中显示为 [] 而不是值(有趣的是,计数显示正常,因此结果看起来像;[] 4 和 [] 2)
  2. 结果作为已部署列和计数的字符串返回,即“on prem 4”而不是两列,on prem, 4

以下是我尝试过的两个视图示例(按照上述两项的顺序):

<% @deployment.each do |e| %>
    <%= e.deployed %> <%= e.count %>
<% end %>


<% @deployment.each do |b| %>
    <% b.each do |bb| %>
     <%= bb %>
        <% end %>
<% end %>

如何在 rails 视图的表格中显示 postgres 数组中项目计数的结果?这是我关于堆栈溢出的第一篇文章,如果我应该提供更多信息,请告诉我。

【问题讨论】:

    标签: ruby-on-rails ruby postgresql


    【解决方案1】:

    我能够对哈希结果使用这种方法

    <% @deployment.each do |key, value| %>
      <%= key %> <%= value %>
    <% end %>
    

    【讨论】:

      【解决方案2】:

      由于查询以散列形式返回结果,因此您必须这样做

       <% @deployment.each do |e| %>
         <%= e['deployed'] %> <%= e['count'] %>
       <% end %>
      

      【讨论】:

      • 谢谢。这仍然对我不起作用。我已经添加了我能够开始工作的答案
      【解决方案3】:

      计数是一个属性,试试这个像

       <% @deployment.each do |e| %>
         <%= e['deployed'] %> <%= e['count'] %>
       <% end %>
      

      【讨论】:

      • 谢谢。这仍然对我不起作用。我已经添加了我能够开始工作的答案
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-09-26
      • 1970-01-01
      • 2019-04-15
      • 1970-01-01
      • 2017-10-16
      • 1970-01-01
      • 2019-07-19
      相关资源
      最近更新 更多