1

Rails 4.2.1 Ruby 2.0.0

I want to display the results of a postgres array count query as a simple table in a rails view. The table should have 2 columns; deployed and count.

I am able to successfully query postgres using the following SQL

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

The results of the postgres query are

deployed | count

on prem  | 4

saas     | 2

I have tried using select_rows and find_by_sql in rails:

@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})

I have tried many different ways to get the data to display as a simple table in a rails view.

The problems that I have faced are:

  1. The string (deploy column) is shown as [] in the view instead of the value (interestingly the count displays fine, so the result looks like; [] 4 and [] 2)
  2. The results are returned as a string of the deployed column and count, i.e. "on prem 4" instead of two columns, on prem, 4

Below are two view examples I have tried (in respective order of the two items above):

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


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

How can I display the results of a count of the items in a postgres array in a table in a rails view? This is my first post on stack overflow so please let me know if I should provide more information.

3 Answers 3

1

I was able to use this approach to the hash results

<% @deployment.each do |key, value| %>
  <%= key %> <%= value %>
<% end %>
Sign up to request clarification or add additional context in comments.

Comments

0

As query returns results in hashes so you would have to do it like this

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

1 Comment

Thank you. This still didn't work for me. I have added an answer with what I was able to get to work
0

Count is an attribute, try this like

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

1 Comment

Thank you. This still didn't work for me. I have added an answer with what I was able to get to work

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.