Display/View result of user sql stmt after find_by_sql

I am trying to support free-form SQL in an internal website and just
take the string and pass it to
find_by_sql. It works fine. But, to show the result I am using the
attributes method of the ActiveRecord:Base class like thus:


<% for task in @tasks %>
  <% if (first == 1) %>
    <% first = 0%>

      <% for column in task.attributes %>
        <th><%= column[0] %></th>
      <% end %>
   <% end %>

  <tr class="<%= cycle("even", "odd") %>">
    <% for column in task.attributes %>
      <td><%= column[1] %></td>
    <% end %>

<% end %>


The funny thing is that the order of columns returned by the
attributes call is neither alphabetical nor the order specified by the
SELECT clause.

What I really would like to do is to display the columns in the order
of the SELECT clause. Any easy way to do this other than parse SELECT
on my own again?

Nope. I am waiting for lightning to strike or to start parsing SELECT
myself :frowning:

Okay, so I figured out a way on my own: Please see my blog post for
the details:


Very nice, I am trying to lean RoR with experimentation and reading
this forum, could you post the code that would gather the find_by_sql


Can you clarify what exactly you are asking? I thought there were enough details in the blog post?

If you cannot see blog here the raw code without the wisdom:

def sqlquery
  if (!querystr.blank?)

    @results = Model.find_by_sql(querystr)
    @total = @results.size()
    if (@total > 0)
        cols = @results.first.attribute_names
        if (querystring.match(/s*SELECTs**s*FROM.*/i))
            @columns = cols

            pos = cols.inject({}) { |h, col| h[col] = querystr.index(col); h}
            @columns = cols.sort { |x,y| pos[x] < => pos[y]}
         @total = 0


  < % for col in @columns %>
       td < %= col %> /td
   < % end %>
      < % for item in @results %>
        < % for col in @columns %>

          td < %= item[col] %> /td
        < % end %>
      < % end %>