簡體   English   中英

如何在 Rails 應用程序中向我的 CSV.generate 端點添加自定義列?

[英]How do I add a custom column to my CSV.generate endpoint in Rails app?

我遵循了這個例子,但我遇到了每行中顯示nil值的問題(在原始值和我添加的附加值之間。

這是我的 controller 端點:

def daily_grocery_carts_overview_export
  @data = DailyRetailerShop.all.order("start_date ASC")
  respond_to do |format|
    format.html { redirect_to root_path }
    format.csv { send_data @data.to_csv, filename: "DailyGroceryCarts-#{Time.now.strftime("%Y%m%d%H%M%S")}.csv" }
  end
end

這是我的 model:

class DailyRetailerShop < ActiveRecord::Base

  def self.to_csv
    # generate site abbreviations & name to add to CSV file
    site_abbreviations = {}
    Partner.all.each do |p|
      site_abbreviations[p[:site_abbreviation]] = p[:name]
    end

    CSV.generate do |csv|
      # remove certain columns
      export_columns = column_names - %w(id site_abbreviation created_at updated_at)
      # add custom column header
      headers = export_columns << 'Website'
      # add to csv file
      csv << headers
      all.each do |item|
        row = item.attributes.values_at(*export_columns).insert(-1, site_abbreviations[item.site_abbreviation])
        csv << row
      end
    end
  end

end

當我下載 CSV 文件並打開它時,我看到一個空白值,然后是我在每一行中附加的自定義值。 如果我閱讀下載的 CSV 文件,以下是我在前幾行中看到的內容:

data = CSV.read("downloaded_file.csv")
puts data[0..3]
=> [["start_date", "grocery_retailer", "retailer_shops", "Website"], ["2019-10-15", "walmart", "25", nil, "Website1"], ["2019-10-15", "walmart", "24", nil, "Website2"], ["2019-10-15", "instacart", "23", nil, "Website3"]]

請注意,每一行都有一個nil值(不在標題中)。 如果我排除我的自定義 header 名稱,然后排除 append 值,就像我所做的那樣,那些nil值(打開文件時為空白)不再存在。

因此,似乎自定義 header 為每一行創建了一個nil值。 我該如何擺脫它?

我從來沒有發現為什么每行都包含這些nil值,但我想出了如何限制它們出現。 以下是我在 model 中修改 function 的方法:

class DailyRetailerShop < ActiveRecord::Base

  def self.to_csv
    # generate site abbreviations & name to add to CSV file
    site_abbreviations = {}
    Partner.all.each do |p|
      site_abbreviations[p[:site_abbreviation]] = p[:name]
    end

    CSV.generate do |csv|
      # remove certain columns
      export_columns = column_names - %w(id site_abbreviation created_at updated_at)
      # add custom column header
      headers = export_columns << 'Website'
      # add to csv file
      csv << headers
      all.each do |item|
        # exclude the last item before inserting site name (custom header)
        row = item.attributes.values_at(*export_columns)[0..-2].insert(-1, site_abbreviations[item.site_abbreviation])
        csv << row
      end
    end
  end

end

希望這對將來的人有所幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM