I did a query in MySql but is working in Rails and mysql2 gem.
Here is the information:
http://sqlfiddle.com/#!2/9adb8/6
The query is working fine without problems and showing this result:
UNIT V1 A1 N1 V2 A2 N2 V3 A3 N3 V4 A4 N4 V5 A5 N5
LIFE 2 0 0 1 2 0 0 0 0 0 0 0 0 0 0
ROB 0 1 0 0 1 2 0 0 0 0 0 0 0 0 0
-Installed mysql2 gem for rails 2.3.8
gem install mysql2 -v0.2.6
-Created the controller:
class PolicyController < ApplicationController
def index
@result = ActiveRecord::Base.connection.execute("select distinct @sql := concat('SELECT pb.name as unit,',group_concat(concat('SUM(CASE WHEN p.state =0 AND ce.id=',id,' THEN 1 ELSE 0 END ) AS v',id,',SUM(CASE WHEN p.state =1 AND ce.id=',id,' THEN 1 ELSE 0 END ) AS a',id,',SUM(CASE WHEN p.state =2 AND ce.id=',id,' THEN 1 ELSE 0 END ) AS n',id)),' FROM cia_ensures ce LEFT JOIN policies p on ce.id = p.cia_ensure_id INNER JOIN policy_business_units pb ON pb.id = p.policy_business_unit_id INNER JOIN comercial_areas ca ON ca.id = pb.comercial_area_id AND ca.id=1 Group by p.policy_business_unit_id') from cia_ensures where id in(1,2,3,4,5);")
@result2 = ActiveRecord::Base.connection.execute("prepare stmt from @sql;")
@result3 = ActiveRecord::Base.connection.execute("execute stmt;")
end
end
Here is the log:
SQL (0.9ms) select distinct @sql := concat('SELECT pb.name as unit,',group_concat(concat('SUM(CASE WHEN p.state =0 AND ce.id=',id,' THEN 1 ELSE 0 END ) AS v',id,',SUM(CASE WHEN p.state =1 AND ce.id=',id,' THEN 1 ELSE 0 END ) AS a',id,',SUM(CASE WHEN p.state =2 AND ce.id=',id,' THEN 1 ELSE 0 END ) AS n',id)),' FROM cia_ensures ce LEFT JOIN policies p on ce.id = p.cia_ensure_id INNER JOIN policy_business_units pb ON pb.id = p.policy_business_unit_id INNER JOIN comercial_areas ca ON ca.id = pb.comercial_area_id AND ca.id=1 Group by p.policy_business_unit_id') from cia_ensures where id in(1,2,3,4,5);
SQL (0.9ms) prepare stmt from @sql;
SQL (0.2ms) execute stmt;
Here is the view (is working fine and without problems but seems to be too long write several times the same code)
<table>
<% @result3.each do |policy| %>
<tr>
<td><%= policy[0] %></td>
<td><%= policy[1] %></td>
<td><%= policy[2] %></td>
<td><%= policy[3] %></td>
<td><%= policy[4] %></td>
<td><%= policy[5] %></td>
...
</tr>
<%end%>
</table>
I tried to use inspect but it shows all the information in one td and not on each td:
<% @result3.each do |policy| %>
<tr>
<td align="center"><%= policy.inspect %></td>
</tr>
<%end%>
How can I do to show all this without writing lots of lines?
Is it possible to make this in one line? without writing <%= policy[#NUMBER] %>
Please somebody can help me with this?
I will really appreciate it.
Hmmm, might have missunderstood your question since it looks really simple, are you trying to shorten this?
Change:
<td><%= policy[0] %></td>
<td><%= policy[1] %></td>
<td><%= policy[2] %></td>
<td><%= policy[3] %></td>
<td><%= policy[4] %></td>
<td><%= policy[5] %></td>
To:
<% policy.each do |p| %>
<td><%= p %></td>
<% end %>