如何在 ActiveRecord 中访问 Mysql::Result?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3658000/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 17:05:11  来源:igfitidea点击:

How to access Mysql::Result in ActiveRecord?

mysqlruby-on-railsactiverecord

提问by ohho

Example:

例子:

result = ActiveRecord::Base.connection.execute("select 'ABC'")

How can I get the 'ABC'value from result? Tried result.firstwithout success. Thanks

我怎样才能从中获得'ABC'价值result?试过result.first没有成功。谢谢

p.s. Gems:

ps宝石:

activerecord (2.3.9)
mysql (2.8.1)

活动记录 (2.3.9)
mysql (2.8.1)

回答by jigfox

You could try it on the cosole:

你可以在cosole上试试:

script/console # rails 2
rails console  # rails 3

enter your code in the console and you get:

在控制台中输入您的代码,您将得到:

irb> result = ActiveRecord::Base.connection.execute("select 'ABC'")
 => [{0=>"ABC", "'ABC'"=>"ABC"}] 

so it you get it with

所以你得到它

result.first[0]
# or
result.first['ABC']

result.firstjust returns the first row, not the first value. This row consists of a Hash with numerical and named access.

result.first只返回第一行,而不是第一个值。该行由具有数字和命名访问权限的哈希组成。

回答by Sytse Sijbrandij

Instead of .executeyou could use .select_all, this will return an array with the result.

而不是.execute你可以使用.select_all,这将返回一个带有结果的数组。

So use:

所以使用:

ActiveRecord::Base.connection.select_all("select 'ABC'")

回答by Shadwell

Try:

尝试:

result = ActiveRecord::Base.connection.select_value("select 'ABC'")

I wouldn't advise messing around with the underlying database code if you don't need to.

如果您不需要,我不建议您弄乱底层数据库代码。