在我的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| %>
<%= tree.sequence %>
<% end %>
我收到错误消息:undefined method 'sequence' for #<Array:0x60e0088>
。
是否有办法循环执行sql查询的结果集并显示每个列值?
非常感谢所提出的所有建议:)
答案 0 :(得分:5)
保持与OP
相同的语法<% @jstree.each do |tree| %>
<%= tree[0] %>
<% end %>
会完成你想要的。
答案 1 :(得分:3)
您收到此错误,因为您在@jstree
中获得的是原始数据库适配器结果。如果要通过发出原始SQL查询来查询某些对象,请使用find_by_sql
。例如:
Client.find_by_sql("SELECT * FROM clients INNER JOIN orders ON clients.id = orders.client_id ORDER clients.created_at desc")