I am trying to get the ordered column names in a result set using
find_by_sql. Perhaps my approach is all wrong, but I am using each .. do. How do I go about keeping the order of the columns as
they appear in the SELECT statement?
For example:
@rows = SomeConnection.find_by_sql "SELECT one,two,three,four FROM
some_table"
@rows.each do |row|
$test = row.attribute_names.join(",")
end
…
<%=$test%>
produces something like:
four,one,three,two
What I would like is for them to keep their order as they appear in
the select statement:
one,two,three,four
…
I hope that is a clear question. Thanks for giving your help!
I am trying to get the ordered column names in a result set using
find_by_sql. Perhaps my approach is all wrong, but I am using each .. do. How do I go about keeping the order of the columns as
they appear in the SELECT statement?
The recordset comes back as a hash, so naturally they’re out of order.
Why not just display the columns in the order you want?
@rows = Person.find_by_sql “SELECT * FROM people;”
<% @rows.each do |row| -%>
<% %w( id name age ).each do |col| -%>
<%= row.send(col) %>
<% end -%>
<% end -%>
I hope that is a clear question. Thanks for giving your help!
One option would be to use the functionality fo the underlying driver
to get the query result in the form that you want. However, you can
use some reflection
to use the order provided by ActiveRecord itself (it might be not
applicable to your own case)
i’m writing an export script that pulls an unknown query and needs to
retain the column names and the column order used in the sql for the
purpose of outputting a spreadsheet to the browser.
that is why this causing me so much grief. i’m using a generic db
connection, not any specific table. i just know the database, but
the query is a join on at least two tables out of many.
i did something similiar to what i am trying to do here with a ruby
script. it uses fetch_fields to get the column info on the result set
after the query has been made. that is essentially what i am looking
for in rails, column information on a query result.
end
@line = []
@line << "\n\r"
@line << @cols.join("\t")
while row = res_xc.fetch_row do
@col = []
row.each do |v|
@col << v
end
@line << @col.join("\t")
end
file = @line.join("\n")
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.