Exporting CSV data from Rails

后端 未结 3 502
孤城傲影
孤城傲影 2021-01-14 10:11

I\'m working to export csv data from rails. I\'m following the tutorial here: http://railscasts.com/episodes/362-exporting-csv-and-excel?view=asciicast

In my control

相关标签:
3条回答
  • 2021-01-14 10:29

    I also met this problem, which was already solved by this answer: https://stackoverflow.com/a/17311372/3458781

    Shortly, you have to restart your server. Hope it works for you.

    0 讨论(0)
  • 2021-01-14 10:36

    The to_csv is a class method. Meaning its meant to be called like Group.to_csv. You might want to change the method signature to something like Group.to_csv(groups) instead.

     def self.to_csv(groups)
        Rails.logger.info "Hello World"
        CSV.generate do |csv|
          csv << column_names
          groups.each do |product|
            csv << product.attributes.values_at(*column_names)
          end
        end
      end
    

    Then in show

      def show
        # @company is being provided correctly.
        @groups = @company.groups
        render text: Group.to_csv(@groups)
      end  
    
    0 讨论(0)
  • 2021-01-14 10:42

    A quick version for rails console that is not for prod but just to have access to the data in excel:

    first do :

    print TableName.first.attributes.map{|a,v| a}.join(",")
    

    second do :

    TableName.all.each{|t| print t.attributes.map{|a,v| a}.join(",") + "\n"}; nil
    

    copy the result of this two call in a csv file

    0 讨论(0)
提交回复
热议问题