我在MySql中进行了查询,但是在Rails和mysql2 gem中工作。
以下是信息:
http://sqlfiddle.com/#!2/9adb8/6
查询正常运行没有问题并显示此结果:
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
- 为rails 2.3.8安装了mysql2 gem
gem install mysql2 -v0.2.6
- 处理控制器:
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
这是日志:
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;
这是视图(工作正常但没有问题,但似乎太长写了几次相同的代码)
<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>
我尝试使用inspect但是它显示了一个td中的所有信息而不是每个td:
<% @result3.each do |policy| %>
<tr>
<td align="center"><%= policy.inspect %></td>
</tr>
<%end%>
如何在不写大量行的情况下显示所有这些内容?
有可能在一行中制作这个吗?无需编写&lt;%= policy [#NUMBER]%&gt;
请有人帮我这个吗?
我真的很感激。
答案 0 :(得分:16)
变化:
<td><%= policy[0] %></td>
<td><%= policy[1] %></td>
<td><%= policy[2] %></td>
<td><%= policy[3] %></td>
<td><%= policy[4] %></td>
<td><%= policy[5] %></td>
要:
<% policy.each do |p| %>
<td><%= p %></td>
<% end %>
答案 1 :(得分:4)
这样做
<% @result3.each do |policy| %>
<tr>
<% policy.each { |p| raw "<td>#{p}</td>" } %>
</tr>
<%end%>
答案 2 :(得分:2)
只需遍历每个policy
对象中的每个集合。
<table>
<% @result3.each do |policy| %>
<tr>
<%policy.each do |item| %>
<td><%= item %></td>
<%end%>
</tr>
<%end%>
</table>