9

In Rails v2.3 , Ruby 1.8, if I run a sql statement with following code in my model class:

ActiveRecord::Base.connection.execute("select count(*) from cars;")

How can I show the query result in server console?

I tried :

rslt = ActiveRecord::Base.connection.execute("select count(*) from cars;")
p rslt

but it only returns me "MySQL result object" on the server console, not the exact result.

Marnen Laibow-Koser
  • 5,959
  • 1
  • 28
  • 33
Mellon
  • 37,586
  • 78
  • 186
  • 264

3 Answers3

13

There are couple ways to get mysql "answer" from your query. you can call each and it will iterate over each row (just one row - count in your case). take a look at mysql gem docs to see other available methods such as each_hash and all_hashes.

rslt = ActiveRecord::Base.connection.execute("select count(*) from cars;")
rslt.each {|mysql_result| puts mysql_result}
Iuri G.
  • 10,460
  • 4
  • 22
  • 39
8

You can just use the to_a method on your result, like so:

result = connection.execute(sql)
result.to_a

This will return (and show if in console) what you're looking for.

yuяi
  • 2,617
  • 1
  • 23
  • 46
1

It depends on the environment you are using currently. For development the default logger level is debug, for production it's info level. You can use it this way:

class HomeController < ActionController::Base
  def index
    rslt = ActiveRecord::Base.connection.execute("select count(*) from cars;")
    logger.info "#{rslt}"
  end
end

You can read more about rails logging on Mike Naberezny's blog: http://mikenaberezny.com/2007/02/24/rails-logging-tips/

Michał Czapko
  • 1,948
  • 1
  • 16
  • 25