【问题标题】:How do you get the rows and the columns in the result of a query with ActiveRecord?如何使用 ActiveRecord 获取查询结果中的行和列?
【发布时间】:2009-11-07 05:29:26
【问题描述】:

有没有办法使用 ActiveRecord 执行自定义 SQL 查询并让它返回一个数组数组,其中第一行是列名,接下来的每一行是行数据?我想执行类似的操作:

connection.select_rows_with_headers "SELECT id, concat(first_name, ' ', last_name) as name, email FROM users"

并让它返回:

[["id","name","email"],["1","Bob Johnson","bob@example.com"],["2","Joe Smith","joe@example.com"]]

这将允许我在 HTML 表格中打印自定义查询的结果,如下所示:

<table>
  <% result.each_with_index do |r,i| %>
    <tr>
      <% r.each do |c| %>
        <% if i == 0 %>
          <th><%=h c %></th>
        <% else %>
          <td><%=h c %></td>
        <% end %> 
      <% end %>
    </tr>
  <% end %>
</table>

请注意,select_all 不起作用,因为每个哈希中的键是无序的,因此您丢失了查询中指定的结果排序。

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    不完全是您正在寻找的,但也许:

    connection.execute('select * from users').all_hashes
    

    你会回来的

    [{:id => 1, :name => 'Bob', :email => 'bob@example.com'},{:id => 1, :name => 'Joe', :email => 'joe@example.com'}]
    

    你可以这样做:

    results = connection.execute('select * from users').all_hashes
    munged_results = []
    columns = results.first.keys.map(&:to_s)
    munged_results << results.first.keys.map(&:to_s)
    munged_results += results.map{|r| columns.map{|c| r[c]} }
    

    类似的东西

    编辑:

    results = connection.execute('select * from users').all_hashes
    munged_results = []
    columns = User.column_names
    munged_results << columns
    munged_results += results.map{|r| columns.map{|c| r[c]} }
    

    应该正确订购。

    除此之外,还有从#execute 返回的结果对象,可以查询一些信息。像#fetch_fields 这样的方法可以按顺序为您获取字段,而#fetch_row 会将结果集中的每一行作为数组获取(就像迭代器一样工作)。

    再次编辑:

    好的,这是一个很好的解决方案,针对您使用的任何数据库进行修改:

    class Mysql::Result
      def all_arrays
        results = []
        results << fetch_fields.map{|f| f.name}
    
        while r = fetch_row
          results << r
        end
    
        results
      end
    end
    

    这将使他们无需大量开销。

    像这样使用它:

    connection.execute('select salt, id from users').all_arrays
    

    【讨论】:

    • 查询并不总是 SELECT *。他们可能具有基于聚合计算等的列或列的子集。我更新了问题以使其更清楚。
    • 是的,all_arrays 正是我想要的。希望有一些非适配器特定的东西,但我相信对于 sqlite、postgres 和 mysql 来说并不难。谢谢!
    • 任何 fetch_fields 等价于较新的 Rails? (3.2.x ?)
    猜你喜欢
    • 1970-01-01
    • 2015-10-30
    • 2012-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-08
    • 2011-04-10
    • 1970-01-01
    相关资源
    最近更新 更多