Here is the code I'm using:
# Run the query against the database defined in .yml file.
# This is a Mysql::result object - http://www.tmtm.org/en/mysql/ruby/
@results = ActiveRecord::Base.connection.execute(@sql_query)
In my View, here's what I do to see the values:
<pre><%= debug @results %></pre>
Outputs: #<Mysql2::Result:0x007f31849a1fc0>
<% @results.each do |val| %>
<%= val %>
<% end %>
Outputs: ["asdfasdf", 23, "qwefqwef"] ["sdfgdsf", 23, "asdfasdfasdf"]
So imagine I query something like select * from Person
, and that returns a result set such as:
ID Name Age
1 Sergio 22
2 Lazlow 28
3 Zeus 47
How can I iterate through each value and output it?
The documentation here is not useful because I have tried methods that supposedly exist, but the interpreter gives me an error saying that those methods don't exist. Am I using the wrong documentation?
http://www.tmtm.org/en/mysql/ruby/
Thanks!
Look for @results.fields for column header.
Example: @results = [[1, "Sergio", 22],[2, "Lazlow", 28],[3, "Zeus", 47]]
Hope it is helpful.
Use
:as => :hash
:If you are using mysql2 gem then you should be getting the mysql2 result object and according to the docs you should be able to do the following
Checkout the documentation here
So in you case you can do the following
Edit: you seem to be referring to the wrong doc check the Mysql2 gems doc.
You could try using
ActiveRecord::Base.connection.exec_query
instead ofActiveRecord::Base.connection.execute
which returns aActiveRecord::Result
(available in rails 3.1+)Then you can access it in various ways like
.rows
,.each
, or.to_hash
From the docs: