Activerecord find_by_sql does not output SQL query results

3.2k views Asked by At

I am using activerecord and find_by_sql to output the results of the sql query:

S = Object.find_by_sql("SELECT * FROM foo")
S.each do |s|
  puts "#{s}"
end

I get

#<Object:0x0000010214d5e0>
#<Object:0x0000010214ce60>

etc...

I need the actual results.

Thanks in advance

Mark

4

There are 4 answers

2
mu is too short On

If you want just the raw unprocessed data from an arbitrary SQL query, you should be using select_rows thusly:

SomeModel.connection.select_rows('select * from foo').each do |row|
  # `row` is an array of strings at this point
  puts row.join(', ')
end

You'll have to sort out type conversions and such yourself but sometimes all the ActiveRecord machinery just gets in the way so you can work with raw SQL and results as needed.

0
Sandip Ransing On

puts converts ruby object into string by invoking to_s method on object.
The default to_s prints the object's class and an encoding of the object id. In order to print human readable form of object use inspect

locs = Location.find_by_sql('select * from locations')
  Location Load (0.5ms)  select * from locations


locs.each do |l|
  # it calls to_s method on object
  puts l
end

#<Location:0x000000055bb328>
#<Location:0x000000055bb058>

locs.each do |l|
  puts l.inspect # prints actual object
end

#<Location id: 15, name: "Annettaside3", street: "71838 Ritchie Cape", city: "East Destanystad", state: "Utah", zip: "58054", phone: 123456, other_phone: 987654, staff_strength: 40, is_active: true, created_at: "2012-01-25 11:17:26", updated_at: "2012-01-25 11:17:26", country_name: "Korea">
#<Location id: 16, name: "Sporerbury4", street: "73057 Jerad Shoal", city: "South Kyliefurt", state: "Delaware", zip: "46553-3376", phone: 123456, other_phone: 987654, staff_strength: 40, is_active: true, created_at: "2012-01-25 11:24:48", updated_at: "2012-01-25 11:24:48", country_name: "Australia">
0
ck3g On

There is no to_s method for that object. You can try puts s.inspect or p s instead

0
Adam Batkin On

The ActiveRecord find_by_sql function expects that the query will return values from the underlying table of the class that it was invoked upon. For example, if you have a class called Foo (with underlying table foos with columns bar and baz) you could do this:

Foo.find_by_sql("select * from foos").each do |record|
    puts "Got a Foo: bar=#{record.bar}, baz=#{record.baz}"
end

If the problem is that you don't like the output you are getting when you try to print out an object (#<Object:0x0000010214d5e0>), then you need only create a to_s method on your class:

class Foo < ActiveRecord::Base
    def to_s
        "Foo bar=#{record.bar}, baz=#{record.baz}"
    end
end

Alternately, don't print the object directly ("#{s}"), use inspect:

puts s.inspect