2014-11-08 44 views
0

當試圖在軌導出CSV文件,我得到這些值僅CSV出口在軌

`#<User:0x007f4a41859980> #<User:0x007f4a41835c88> 

我控制器文件ps4_controller.rb

def csv_export 
    @users = User.order(created_at: :desc) 
    respond_to do |format| 
     format.html 
     format.csv { render text: @users.to_csv } 
     format.xls { render text: @users.to_csv(col_sep: "\t") } 
    end 
    end 

模型文件ps4.rb

class Ps4 < ActiveRecord::Base 
    attr_accessible :username, :email, :school, :batch 

    def self.to_csv(users) 
     CSV.generate do |csv| 
     csv << column_names 
     users.each do |ps4| 
      csv << ps4.attributes.values_at(*column_names) 
     end 
     end 
    end 
end 

查看文件csv_export.xls.rb

<table> 
    <thead> 
    <tr> 
     <th>Username</th> 
     <th>Email</th> 
     <th>School</th> 
     <th>Batch</th> 
    </tr> 
    </thead> 
    <tbody> 
    <% @users.each do |user| %> 
     <tr> 
      <td><%= user.username %></td> 
      <td><%= user.email %></td> 
      <td><%= user.school %></td> 
      <td><%= user.batch %></td> 
     </tr> 
    <% end %> 
    </tbody> 
</table> 

有人可以幫忙嗎?

回答

1

@users是一個用戶數組,你試圖在數組上調用to_csv方法。在另一方面,to_csv方法被定義爲一個類的方法,這意味着你需要調用它的類本身:

format.csv { render text: User.to_csv(@users) } 
2

在控制器:

respond_to do |format| 
    ... 
    format.csv { send_data @users.to_csv, filename: "users-#{Date.today}.csv" } 
end 

在模型(不發送任何屬性至to_csv方法):

def self.to_csv 
    attributes = %w{id email} 

    CSV.generate(headers: true) do |csv| 
    csv << attributes 

    all.each do |user| 
     csv << attributes.map{ |attr| user.send(attr) } 
    end 
    end 
end