2011-10-31 79 views
3

在我的Rails應用程序中,我的控制器頁面中有一個以下函數。執行SQL查詢並循環遍歷結果集在rails中

def tree 
@jstree = ActiveRecord::Base.connection.execute("Select sequence, depth, node, imageid, range from.....several joins") 
end 

我現在通過ResultSet要循環,只有在我看來tree.html.erb頁面顯示順序。我嘗試了下面的代碼,它似乎沒有工作。

<% @jstree.each do |tree| %> 
<%= tree.sequence %> 
<% end %> 

我收到錯誤消息:undefined method 'sequence' for #<Array:0x60e0088>

是否有一種方法可以循環執行sql查詢的結果集並顯示每個列值?所有建議

很多很多的感謝提供:)

+0

您使用的是哪種版本的導軌和數據庫適配器? –

+0

正在使用rails 2.3.5和mysql適配器 – tanya

回答

3

你得到這個錯誤,因爲你在@jstree得到的是一個原始的DB適配器結果。如果要通過發出原始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") 
+0

非常感謝,它的確有竅門:) – tanya

+0

在這種情況下,什麼是'Client'? – Catfish

+0

@Catfish你的模型。 – DnfD

5

保持相同的語法OP

<% @jstree.each do |tree| %> 
<%= tree[0] %> 
<% end %> 

將完成你所期待的。