rails,无法在视图中显示postgres数组计数结果

时间:2015-05-06 10:42:58

标签: ruby-on-rails ruby postgresql

Rails 4.2.1 Ruby 2.0.0

我希望将postgres数组计数查询的结果显示为rails视图中的简单表。该表应该有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 the,4
  3. 以下是我尝试的两个视图示例(按上述两项的相应顺序):

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

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

3 个答案:

答案 0 :(得分:1)

我能够将这种方法用于哈希结果

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

答案 1 :(得分:0)

Count是一个属性,请尝试

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

答案 2 :(得分:0)

当查询返回哈希值时,你必须像这样做

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