Search code examples
ruby-on-railsruby-on-rails-5

Rails export to csv through associations


I have an issue with associations and download via csv export.

My export works if data is present in the sales association, but if there is no data my export remains blank. Removing the i.sales.each do part will export i.item_name and i.item_number fields fine.

So, if there is no data in my association my export remains blank. Is there a method to check if an association has information? I'm looking to include blank fields if no data is present.

I've tried i.try(:sales).each do |sale| to no avail.

CSV.generate(headers: true) do |csv|
  csv << attributes
  all.each do |i|
    i.sales.each do |sale|
      csv << [
          i.item_name,
          i.item_number,
          sale.try(:sale_cost)
      ]
     end
   end
 end

Solution

  • You need to use left join to get all the records from the first table. This will give you NULL values for the associated table, just as you want.

    NOTE: Please change the references of Product model/table with the appropriate one.

    Rails 5 and above

    left_joins(:sales).select('products.*, sales.sale_cost').each do |product|
      csv << [
        product.item_name,
        product.item_number,
        (product.sale_cost || 'N/A')
      ]
    end
    

    Rails 4 and below

    Product.joins("left join sales on products.id = sales.product_id")
           .select('products.*, sales.sale_cost')
           .each do |product|
    
      csv << [
        product.item_name,
        product.item_number,
        (product.sale_cost || 'N/A')
      ]
    end
    

    This will result in something like:

    pencil,12345,20
    pencil,12345,10 
    eraser,11223,5
    box,11333,N/A