Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 639
Curious_Bop Avatar asked Apr 20 '26 09:04

Curious_Bop


1 Answers

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]
like image 102
ABrowne Avatar answered Apr 22 '26 23:04

ABrowne



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!