【问题标题】:Activerecord find_by_sql does not output SQL query resultsActiverecord find_by_sql 不输出SQL查询结果
【发布时间】:2012-01-30 17:59:19
【问题描述】:

我使用activerecord和find_by_sql输出sql查询的结果:

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

我明白了

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

等等……

我需要实际的结果。

提前致谢

标记

【问题讨论】:

  • 根据您的描述,它看起来工作正常,您期待什么?
  • 您使用SELECT * 选择的属性是什么?如果其中一个属性是例如一个name,然后你可以调用s.name等

标签: sql ruby activerecord find-by-sql


【解决方案1】:

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

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

如果问题是您不喜欢尝试打印对象时得到的输出 (#&lt;Object:0x0000010214d5e0&gt;),那么您只需在您的类上创建一个 to_s 方法:

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

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

puts s.inspect

【讨论】:

    【解决方案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 和结果。

    【讨论】:

    • 太棒了! ...有没有办法知道返回的列的名称? (当我在我的 sql 语句中有“左连接”时,find_by_sql 和其他 activerecord 方法会失败)
    • @Abdo:select_rows 不适用,它只为每一行返回一个数组,并且行数组的元素与 SELECT 列的顺序相同。
    【解决方案3】:

    该对象没有to_s 方法。 你可以试试puts s.inspect 或p s 代替

    【讨论】:

      【解决方案4】:

      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">
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-09-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-07-12
        相关资源
        最近更新 更多