如何遍历所有记录并将数据库值传递给变量?

时间:2014-10-15 18:21:54

标签: ruby-on-rails ruby database nokogiri

我有两张桌子," Que"和" Opts"。

我想遍历Que中的所有记录,并将它们添加到变量rikt_nrstart_nrend_nr,因为它们将放在URL的末尾,这将是看起来像:

api.url.number=8-00001

如何让它在Que中进行迭代并将rikt_nrstart_nrend_nr传递给代码的其余部分?

Que表包含以下字段:

create_table "ques", force: true do |t|
  t.integer  "rikt_nr"
  t.integer  "start_nr"
  t.integer  "end_nr"
  t.datetime "created_at"
  t.datetime "updated_at"
end

和Opts有这些字段:

create_table "opts", force: true do |t|
  t.string   "numbers"
  t.string   "operator"
  t.datetime "created_at"
  t.datetime "updated_at"
end

这是代码:

Que.all.each do | que |

  url = "http://api.url.number=" 

  que.rikt_nr = rikt_nr 
  que.start_nr = start_nr  
  que.end_nr = end_nr  
  st_en = start_nr..end_nr 

  st_en.each do |nr| 
    full_url = "#{url}" + rikt_nr.to_s + "-"+ nr.to_s

    doc = Nokogiri::XML(open(full_url)) 

    number = doc.at('Number').text  
    operator = doc.at('Name').text 

    number_operator = "#{number}" + ";" + " #{operator}"

    number_operator 

    save = @opts.create(:numbers => number, :operator => operator) 
  end
end

1 个答案:

答案 0 :(得分:0)

我刚发现了这个。

问题在于:

que.rikt_nr = rikt_nr 
que.start_nr = start_nr  
que.end_nr = end_nr  
st_en = start_nr..end_nr

所以我改成了:

Que.all.each do | que |

  url = "http://api.url.number=" 

  st_en = que.start_nr..que.end_nr 

  st_en.each do |nr| 
    full_url = "#{url}" + que.rikt_nr.to_s + "-"+ nr.to_s

    doc = Nokogiri::XML(open(full_url)) 

    number = doc.at('Number').text  
    operator = doc.at('Name').text 

    number_operator = "#{number}" + ";" + " #{operator}"

    number_operator 

    save = @opts.create(:numbers => number, :operator => operator) 

  end
end

它现在有效。