Activerecord find_by_sql 不输出SQL查询结果
我正在使用 activerecord
和 find_by_sql
输出 sql 查询的结果:
S = Object.find_by_sql("SELECT * FROM foo")
S.each do |s|
puts "#{s}"
end
我得到
#<Object:0x0000010214d5e0>
#<Object:0x0000010214ce60>
等等...
我需要实际结果。
预先感谢
马克
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
ActiveRecord
find_by_sql
函数期望查询将从调用它的类的基础表中返回值。例如,如果您有一个名为Foo
的类(其基础表foos
包含列bar
和baz
),您可以这样做:如果问题是您不喜欢尝试打印对象时获得的输出 (
#
),那么您只需创建一个类上的to_s
方法:或者,不要直接打印对象 (
"#{s}"
),使用inspect
: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 calledFoo
(with underlying tablefoos
with columnsbar
andbaz
) you could do this: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 ato_s
method on your class:Alternately, don't print the object directly (
"#{s}"
), useinspect
:如果您只需要来自任意 SQL 查询的原始未处理数据,则应该使用
select_rows
因此:您必须自己整理类型转换等,但有时所有 ActiveRecord 机制都会得到这样您就可以根据需要使用原始 SQL 和结果。
If you want just the raw unprocessed data from an arbitrary SQL query, you should be using
select_rows
thusly: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.
该对象没有
to_s
方法。您可以尝试使用
puts s.inspect
或p s
代替There is no
to_s
method for that object.You can try
puts s.inspect
orp s
insteadputs
通过调用对象上的 to_s 方法将 ruby 对象转换为字符串。默认的
to_s
打印对象的类和对象 ID 的编码。为了打印人类可读的对象形式,请使用
inspect
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