27

Example:

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

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

p.s. Gems:

activerecord (2.3.9)
mysql (2.8.1)

3 Answers 3

29

You could try it on the 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.first just returns the first row, not the first value. This row consists of a Hash with numerical and named access.

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks jigfox. For the result [{0=>"ABC", "'ABC'"=>"ABC"}], why there is 2 "ABC"s? and, what is the meaning of 0 and first "'ABC'"? Is one of them a column name? As when I do the query in MySQL Query Browser, the column name is ABC and the value is first row is ABC.
result is #<Mysql::Result:0x102f5e0d0> instead of [{0=>"ABC", "'ABC'"=>"ABC"}]. What gives?
"why there is 2 "ABC"s? and, what is the meaning of 0 and first "'ABC'"?" One is accessible by the Column number "1" and one is accessible by the column name "ABC".
as to your mysql result: it shouldn't matter, you should still be able to access you values like in a array of hashs.
@ohho - Ran into the same issue/question. We are using an old version of Ruby/Rails and MySQL. In the script/console changed it to ActiveRecord::Base.connection.select_one("select 'ABC'") and got back something sensible...
26

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

So use:

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

1 Comment

This returns an ActiveRecord::Result.
23

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.

2 Comments

Thanks Shadwell. I give the answer credit to jigfox as I am looking for the general return structure from a MySQL query, not limited to a value. A useful credit for you ;-)
with 500k+ records you really can't do select all because of the speed. This is also usually the reason people tend to use connection.execute so they can optimize the SQL being processed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.