Rails:如何select_rows与字段名称(mysql)

时间:2013-10-06 17:11:24

标签: mysql ruby-on-rails activerecord

我正在寻找一种方法来获取类似于ActiveRecord :: Base.connection.select_rows输出的mysql查询的结果集,但也包括结果的列名作为第一个元素。

例如:

ActiveRecord::Base.connection.select_rows_with_fields("SELECT id,name FROM users")
     => [["id", "name"], ["1","amy"],["2","bob"],["3","cam"]]

1 个答案:

答案 0 :(得分:1)

select_rows_with_fields:

module ActiveRecord
  module ConnectionAdapters
    class Mysql2Adapter
      def select_rows_with_fields(sql)
        result = execute(sql)
        rows = result.to_a
        rows.unshift(result.fields)
      end
    end
  end
end