Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

execute sql query and loop through result set in rails

In my rails app, i have the following function in one of my controller page.

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

I now want to loop through the resultset and display the sequence only in my view page tree.html.erb. I tried the following code, it does not seem to work.

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

I am getting the error message: undefined method 'sequence' for #<Array:0x60e0088>.

Is there a way of looping through the result set of the sql query executed and displaying each column value?

Many many thanks for all suggestion provided :)

like image 940
tanya Avatar asked Aug 27 '26 02:08

tanya


2 Answers

Keeping the same syntax as the OP

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

would accomplish what you were looking for.

like image 181
Alex Muro Avatar answered Aug 29 '26 16:08

Alex Muro


You get this error because what you get in @jstree is a raw DB adapter result. If you want to query for some objects by issuing raw SQL queries then use find_by_sql. Example:

Client.find_by_sql("SELECT * FROM clients INNER JOIN orders ON clients.id = orders.client_id ORDER clients.created_at desc")
like image 42
Ion Br. Avatar answered Aug 29 '26 16:08

Ion Br.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!