Atsu Mori
Atsu Mori

Reputation: 11

Store the output of results.each into array in ruby on rails

Code:

 {   db = Mysql2::Client.new( :host => 'localhost', :username => 'username',
  password => 'password', :database => 'database')

results = db.query("select * from users where exported is not TRUE OR 
  NULL").each(:as => :array)

results.each { | row | puts row[1]}

The results.each line outputs outputs company data, and I want to use each line as an input within an API call. Any ideas as how to do this? Each row should populate an attribute like below.

"requested_item_value_attributes" => {
    "employee_first_name_6000555821" => 'results.each { | row | puts row[0]}',
    "employee_last_name_6000555821" => "results.each { | row | puts row[1]}",
    "hiring_manager_6000555821" => "results.each { | row | puts row[2]}",
    "job_title" => "results.each { | row | puts row[3]}",
    "start_date" => "#results.each { | row | puts row[4]}"
  } 

Upvotes: 1

Views: 2452

Answers (3)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

Use [Array#map] to map the results to an array:

results.map do |row|
  "requested_item_value_attributes" => {
    "employee_first_name_6000555821" => row[0],
    "employee_last_name_6000555821" => row[1],
    "hiring_manager_6000555821" => row[2],
    "job_title" => row[3],
    "start_date" => row[4]
  }
}

or, even better:

results.map do |row|
  "requested_item_value_attributes" => 
    %w[
      employee_first_name_6000555821,
      employee_last_name_6000555821,
      hiring_manager_6000555821,
      job_title,
      start_date
    ].zip(row.take(5)).to_h
  }
}

Upvotes: 0

justapilgrim
justapilgrim

Reputation: 6872

Use the query method second argument.

results = []
db.query('SELECT * FROM table', results)

Upvotes: 0

FlyingFoX
FlyingFoX

Reputation: 3509

You can use

nameArray = Array.new
nameArray.push(nameToSave)

to add the variable nameToSave to the end of the array nameArray. Just call push for each of your results and you have an array with all your names from your query.

Upvotes: 1

Related Questions