How to Iterate through Column Names from execute sql results
I'm trying to iterate thr开发者_StackOverflowough each column name from my results to place in the first row of my view. I'm using the execute sql way to querying the database.
I've got this so far but it's not outputting what I need:
<% for columns in @results %>
<tr>
<% @results.each do |column, value| %>
<td><%= column %></td>
<% end %>
</tr>
<% end %>
For the people coming here 2.5 years after this was asked, I was able to do this with Rails 3.2.13 and Ruby 1.9.3-p194:
result=ActiveRecord::Base.connection.select_all("SELECT id AS 'user_id', first_name AS 'name' FROM users LIMIT 1")
result.each do |row|
row.each do |k, v|
puts "column #{k} contains #{v}"
end
end
Result:
column user_id contains 1
column name contains Me
[{"user_id"=>1, "name"=>"Me"}]
Access it:
result.first["user_id"]
And if there are 3 results and you want to get the 2nd one:
result[1]["user_id"]
Look up: MySQL/Ruby (http://www.tmtm.org/en/mysql/ruby/) if you're iterating a MySQL database. Other databases, look up the other drivers. Speaking purely about MySQL/Ruby, the result returned is a Mysql::Result
.
You iterate this using each_hash
and the block yields a hash for the row. You can then iterate the hash using each_pair. E.g.:
result = MyModel.connection.execute('select * from foos')
result.each_hash do |row|
row.each_pair do |k, v|
puts "column #{k} contains #{v}"
end
end
精彩评论