CSV导出轨道

时间:2014-11-08 15:13:08

标签: ruby-on-rails-4

在rails中尝试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>

有人可以帮忙吗?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

@users是一组用户,您尝试在阵列上调用to_csv方法。另一方面,to_csv方法被定义为类方法,这意味着您需要在类本身上调用它:

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