如何使用 ActiveRecord 获取查询结果中的行和列?

2024-04-30

有没有办法使用 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","[email protected] /cdn-cgi/l/email-protection"],["2","Joe Smith","[email protected] /cdn-cgi/l/email-protection"]]

这将允许我在 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不起作用,因为每个散列中的键都是无序的,因此您丢失了查询中指定的结果的顺序。


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

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

你会回来的

[{:id => 1, :name => 'Bob', :email => '[email protected] /cdn-cgi/l/email-protection'},{:id => 1, :name => 'Joe', :email => '[email protected] /cdn-cgi/l/email-protection'}]

你可以这样做:

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]} }

类似的东西

edit:

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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 ActiveRecord 获取查询结果中的行和列? 的相关文章

随机推荐