Activerecord find_by_sql不输出SQL查询结果

时间:2012-01-30 17:59:20

标签: sql ruby activerecord find-by-sql

我使用activerecordfind_by_sql输出sql查询的结果:

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

我得到了

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

等...

我需要实际结果。

提前致谢

标记

4 个答案:

答案 0 :(得分:3)

ActiveRecord find_by_sql函数期望查询将从调用它的类的基础表返回值。例如,如果您有一个名为Foo的类(基础表foos包含列barbaz),您可以这样做:

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

如果问题是您不喜欢在尝试打印对象(#<Object:0x0000010214d5e0>)时获得的输出,那么您只需要在类上创建to_s方法:

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

或者,不要直接打印对象("#{s}"),使用inspect

puts s.inspect

答案 1 :(得分:2)

如果您只想要来自任意SQL查询的原始未处理数据,那么您应该使用select_rows

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

你必须自己整理类型转换,但有时候所有的ActiveRecord机器都会受到阻碍,因此你可以根据需要使用原始SQL和结果。

答案 2 :(得分:0)

该对象没有to_s方法。 您可以尝试使用puts s.inspectp s

答案 3 :(得分:0)

puts通过在对象上调用to_s方法将ruby对象转换为字符串 默认to_s打印对象的类和对象id的编码。 为了打印人类可读形式的对象,请使用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">