Search code examples
mysqlruby-on-railsarraysrubymysql2

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]}"
  } 

Solution

  • 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
      }
    }