2014-11-08 5 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