Search code examples
ruby-on-railsactiverecordruby-on-rails-2

How to show sql result on server console


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.


Solution

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