将 results.each 的输出存储到 rails 上的 ruby 中的数组中
Store the output of results.each into array in ruby on rails
代码:
{ 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]}
results.each
行输出公司数据,我想将每一行用作 API 调用中的输入。关于如何做到这一点的任何想法?每行应填充如下所示的属性。
"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]}"
}
您可以使用
nameArray = Array.new
nameArray.push(nameToSave)
将变量nameToSave
添加到数组nameArray
的末尾。
只需为每个结果调用 push
,您就会得到一个包含查询中所有姓名的数组。
使用 query
方法第二个参数。
results = []
db.query('SELECT * FROM table', results)
使用 [Array#map
] 将 results
映射到数组:
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]
}
}
或者,甚至更好:
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
}
}
代码:
{ 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]}
results.each
行输出公司数据,我想将每一行用作 API 调用中的输入。关于如何做到这一点的任何想法?每行应填充如下所示的属性。
"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]}"
}
您可以使用
nameArray = Array.new
nameArray.push(nameToSave)
将变量nameToSave
添加到数组nameArray
的末尾。
只需为每个结果调用 push
,您就会得到一个包含查询中所有姓名的数组。
使用 query
方法第二个参数。
results = []
db.query('SELECT * FROM table', results)
使用 [Array#map
] 将 results
映射到数组:
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]
}
}
或者,甚至更好:
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
}
}