Note that there are some explanatory texts on larger screens.

plurals
  1. POExport as CSV accessing elements of an array and inserting line breaks
    text
    copied!<p>I have a document stored in Mongo inside the jobs collection that looks like this:</p> <pre><code>"products" : [ { "id" : "51bc0cc39727911120000145", "price" : 19, "quantity" : 1, "tax" : 0 }, { "id" : "51bc0cc39727911120000171", "price" : 14, "quantity" : 1, "tax" : 0 }, { "id" : "51bc0cca9727911120000a23", "price" : 308, "quantity" : 1, "tax" : 0.092500001192093 } ] </code></pre> <p>products is an array of arrays. When you export as CSV, this entire line prints out when you access the "products" key (naturally).</p> <p>What I need to do:</p> <p>Reach inside products and grab EACH of the elements, printing them in appropriate columns in the CSV AND inserting a line break in the CSV such that they line up under the appropriate columns.</p> <p>Something like:</p> <p>ID PRICE QUANTITY TAX ID PRICE QUANTITY TAX ID PRICE QUANTITY TAX</p> <p>Line 1 above to the left has the actual JOB NUMBER, but lines 2 and 3 wouldn't have that (it would be redundant).</p> <p>The crazy part is I need some each logic that will grab however many parts are added to the job (from none to infinity).</p> <p>Does anyone have any idea how to pull this off?</p> <p>I'm using the comma gem, so I have some code in my model:</p> <p>products do |products| #I've tried untold combos here - none of which work end</p> <p>Help!</p> <p>UPDATE:</p> <p>Something like this gets the first element out of products (and payments which is structured the same)</p> <pre><code>products do |products| products.each do |p| @pid = p["id"] @pid = Inventory.find_by_id(@pid) if @pid == nil @pid = "None" else @pid = @pid.parts_name end end @pid end products 'Price' do |products| products.each do |p| @price = p["price"] end @price end products 'Quantity' do |products| products.each do |p| @qty = p["quantity"] end @qty end products 'Tax' do |products| products.each do |p| @tax = (p["tax"].to_f * (p["price"].to_f * p["quantity"].to_i)).round(2) end @tax end </code></pre> <p>Any idea on for loop logic ?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload