0

我正在使用activerecordandfind_by_sql来输出 sql 查询的结果:

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

我明白了

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

ETC...

我需要实际的结果。

提前致谢

标记

4

4 回答 4

3

如果您只想要来自任意 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 和结果。

于 2012-01-30T18:52:38.887 回答
3

ActiveRecordfind_by_sql函数期望查询将从调用它的类的基础表中返回值。例如,如果您有一个名为(带有带有列和Foo的基础表)的类,您可以这样做:foosbarbaz

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
于 2012-01-30T18:07:54.803 回答
0

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

于 2012-01-30T18:07:19.877 回答
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">
于 2012-01-30T19:31:37.083 回答