ohho
ohho

Reputation: 51941

How to access Mysql::Result in ActiveRecord?

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)

Upvotes: 27

Views: 28379

Answers (3)

Sytse Sijbrandij
Sytse Sijbrandij

Reputation: 1905

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

Upvotes: 26

jigfox
jigfox

Reputation: 18177

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.

Upvotes: 29

Shadwell
Shadwell

Reputation: 34774

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.

Upvotes: 23

Related Questions