6

I have a rather complex sql statement that is created on the fly. But the same problem exists for a simple query, so I use this one as an example.

I have a Feature model. I can call Feature.count --> 4

But if I try to get all Feature ids using ActiveRecord::Base.connection.execute("SELECT ID from features") the result is a OCI8::Cursor object. I do not know how to get the data out of it.

If I try ActiveRecord::Base.connection.execute("SELECT ID from features").fetch I get [1]. With xyz.fetch_hash I get {"ID" => 1}.

I would like to have all IDs. I just switched from PostgreSQL to Oracle.

Using PostgreSQL, I got all data using ActiveRecord::Base.connection.execute("SELECT ID from features").to_a, but to_a does not exist using the activerecord-oracle_enhanced-adapter gem (*** NoMethodError Exception: undefined method 'to_a' for #<OCI8::Cursor:0x00000007028aa8>).

I am using Ruby 2.0 and Rails 4. The connection to the Oracle database is working, except my manually created statement.

2 Answers 2

13

I found a solution.

Old: ActiveRecord::Base.connection.execute("SELECT ID from features")

New: ActiveRecord::Base.connection.exec_query("SELECT ID from features").to_a

Maybe someone have the same problem.

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

3 Comments

Why don't you use the pluck method for this? ie: Feature.pluck(:id)
Because this was an example. I had the same problem with a complex sql statement. But I thought it is easier to explain and to understand if I use Feature as an example.
@Bjoernsen absolutely right. I'm working on a project where the sql queries are quite complex and ActiveRecord make more problems than it solves! Thanks a lot!
1

my solution

  def my_exec_query(sql)
    # because our old framework does not have exec_query
    res = ActiveRecord::Base.connection.execute(sql)
    res_data = []
    res.fetch_hash { |d| res_data << d }
    res.close

    res_data
  end

Comments

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.