问题
I have two tables, "Que" and "Opts".
I want to iterate through all the records in Que and add them to the variables rikt_nr
, start_nr
and end_nr
, because they will go on the end of a URL, which will look like:
api.url.number=8-00001
How do I make it iterate through Que and pass rikt_nr
, start_nr
and end_nr
to the rest of the code?
The Que table has these fields:
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
and Opts has these fields:
create_table "opts", force: true do |t|
t.string "numbers"
t.string "operator"
t.datetime "created_at"
t.datetime "updated_at"
end
This is the code:
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:
I just found out this.
The problem was here:
que.rikt_nr = rikt_nr
que.start_nr = start_nr
que.end_nr = end_nr
st_en = start_nr..end_nr
so I changed it to:
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
and it now works.
来源:https://stackoverflow.com/questions/26389455/how-do-i-iterate-through-all-records-and-pass-database-value-to-a-variable