Curious_Bop
Curious_Bop

Reputation: 311

Ruby activerecord result to array

My aim is to take the result of my activerecord search and print it into a nice array but the print part is where I am having trouble.

I first build my oracle connection with the following which works in isolation.

  def oracle_connection(adapter, database, username, password)
    begin
      ActiveRecord::Base.establish_connection(
          adapter: adapter,
          database: database,
          username: username,
          password: password)
    end
  end

I then create my query with the following function:

def query
      "select * from owner.appn where appn_id = #{$id}"
end

And here is the part where I am asking the question on. I want to pass the result of the query being returned out into an 2D array. Below is what I currently have to execute the active connection query.

  def oracle_query_into_array(query)
    result_set = ActiveRecord::Base.connection.execute(query)
    if result_set.present?
#add logic here
    else
      return nil
    end
  end

Thanks

Upvotes: 3

Views: 8899

Answers (1)

ABrowne
ABrowne

Reputation: 1604

I'm assuming you have reasons to use the underlying connection calls rather than the abstractions that are common practise.

With the ActiveRecord::Base.connection.execute(query) I would expect this to return true if it executes. What you want is a cursor on the data, so try this:

result = ActiveRecord::Base.connection.exec_query(query)
puts result.to_a
=> [array of results]

A usual abstraction (ActiveRecord::Base) would take the form of creating a model to represent your data, so in your case, this could look like:

class Appn < ActiveRecord::Base
end

This will be automatically mapped to a table within your connection called Appnn allowing you to update the above code to:

results = Appn.where(appn_id: $id)
puts results.to_a
=> [array of results]

Upvotes: 2

Related Questions