Mani kandan
Mani kandan

Reputation: 261

Export as CSV in Rails with association model values

In my project one of the features is to export data as CSV.

I have written a function in the model to do this, which works fine but what if I wanted to export the associated model values in the same CSV file?

I tried multiple methods but didn't succeed.

Product.rb:

has_many :product_other_informations

def self.to_csv
  CSV.generate do |csv|
    csv << ["Name", "Description", "Tags", "Meta_keywords", "Page_title", "Meta_description", "Slug", "Published_status", "Other_information", "Other_information_value"]
    all.each do |product|
      csv << [product.name, product.description, product.tags, product.meta_keywords, product.page_title, product.meta_description, product.slug, product.is_published]
    end
  end
end

This is used to export only product values. What do I do if I want to export "product other information" model values in the same CSV?

Upvotes: 5

Views: 3320

Answers (1)

Cody Caughlan
Cody Caughlan

Reputation: 32758

You need to first determine if you have other information to display and if so, how you are going to display potentially multiple rows in one CSV "cell". Maybe you include just the name attribute (assuming there is a product_other_information.name attribute) and comma-delimit multiple.

In which case your loop would look something like:

def self.to_csv
CSV.generate do |csv|
  csv << ["Name", "Description", "Tags", "Meta_keywords", "Page_title", "Meta_description", "Slug", "Published_status", "Other_information", "Other_information_value"]
  all.each do |product|
    if product.product_other_informations.any?
      row = [product.name, product.description, product.tags, product.meta_keywords, product.page_title, product.meta_description, product.slug, product.is_published]
      other = product.product_other_informations.collect { |o| o.name }.join(", ")
      row << other
      csv << row
    else
      csv << [product.name, product.description, product.tags, product.meta_keywords, product.page_title, product.meta_description, product.slug, product.is_published, nil]
    end
  end
end

Upvotes: 4

Related Questions