I am working on a piece of code that writes data from 4 different .each blocks into 4 different MySQL rows in a table.
Edit: I should note that these four blocks are nested in one loop. I’ve figured out that it is stacking each db.query on top of the one before because it is generating a new ID for each of them. So, the code IS working…just not as intended. Basically, one row in the table should contain a column and corresponding data for a, b, c, and d. How can I use multiple blocks like this and make sure they’re all writing to the same row?
The code looks a bit like this…
1.upto(5) do |num|
a.each do |a|
puts a
db.query("INSERT INTO Table(Column1) VALUES('#{a}')")
end
b.each do |b|
puts b
db.query("INSERT INTO Table(Column2) VALUES('#{b}')")
end
c.each do |c|
puts c
db.query("INSERT INTO Table(Column3) VALUES('#{c}')")
end
d.each do |d|
puts d
db.query("INSERT INTO Table(Column4) VALUES('#{d}')")
end
end
Obviously this is just an example but the blocks don’t really differ much from this.
A few things.
First, yes, I need to have these four blocks with the .each because I am doing different things with them that I can’t just do all in one block.
Second, I know that each of these blocks is “right” because if I comment out all of them but one, it will write perform that one block correctly – writing to the database, etc. With all of the blocks uncommented like they should be, it only writes block ‘a’ to the database and the rest of the blocks don’t write anything, leaving the rows NULL.
The ‘puts’ commands are outputting perfectly fine as expected – each block executing after the one before, there is just an issue when it is trying to do the query() method.
Any ideas?
I’ve never used Ruby before but perhaps you have an issue with disposing of the query object or properly initialising it again before using it for subsequent blocks?
Try re-initialising the query object.