【问题标题】:How do I add a custom column to my CSV.generate endpoint in Rails app?如何在 Rails 应用程序中向我的 CSV.generate 端点添加自定义列?
【发布时间】:2019-10-29 05:31:19
【问题描述】:

我关注了this example,但我遇到了nil 值出现在每一行中的问题(在原始值和我添加的附加值之间。

这是我的控制器端点:

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

这是我的模型:

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 值(不在标题中)。如果我排除我的自定义标题名称,然后像我在那些 nil 值(打开文件时为空白)之上所做的那样附加值,则不再存在。

因此,自定义标题似乎为每一行创建了一个nil 值。我该如何摆脱它?

【问题讨论】:

    标签: ruby-on-rails csv export


    【解决方案1】:

    我从来不知道为什么那些nil 值会包含在每一行中,但我想出了如何限制它们出现。以下是我在模型中修改函数的方式:

    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
    

    希望这对将来的某人有所帮助!

    【讨论】:

      猜你喜欢
      • 2012-09-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多