Ruby on rails 在rails中执行sql查询并循环结果集
在我的rails应用程序中,我的一个控制器页面中有以下功能Ruby on rails 在rails中执行sql查询并循环结果集,ruby-on-rails,Ruby On Rails,在我的rails应用程序中,我的一个控制器页面中有以下功能 def tree @jstree = ActiveRecord::Base.connection.execute("Select sequence, depth, node, imageid, range from.....several joins") end 现在,我想循环遍历结果集,只在我的视图页面tree.html.erb中显示序列。我尝试了以下代码,它似乎不起作用 <% @jstree.each do |tree| %
def tree
@jstree = ActiveRecord::Base.connection.execute("Select sequence, depth, node, imageid, range from.....several joins")
end
现在,我想循环遍历结果集,只在我的视图页面tree.html.erb
中显示序列。我尝试了以下代码,它似乎不起作用
<% @jstree.each do |tree| %>
<%= tree.sequence %>
<% end %>
我收到错误消息:的未定义方法“序列”
是否有方法循环执行sql查询的结果集并显示每个列值
非常感谢您提供的所有建议:)您会收到此错误,因为您在
@jstree
中得到的是原始数据库适配器结果。如果要通过发出原始SQL查询来查询某些对象,请使用find\u by\u SQL
。例如:
Client.find_by_sql("SELECT * FROM clients INNER JOIN orders ON clients.id = orders.client_id ORDER clients.created_at desc")
保持与OP相同的语法
<% @jstree.each do |tree| %>
<%= tree[0] %>
<% end %>
将完成您所寻找的。您使用的是哪个版本的rails和哪个数据库适配器?我使用的是rails 2.3.5和mysql适配器在这种情况下,什么是
客户端?@Catfish您的模型。