nas
nas

Reputation: 2437

CSV Export in rails

When trying csv export in rails, I am getting these values only

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

my controller file 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

model file 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

view file 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>

Can anybody plz help?

Upvotes: 0

Views: 340

Answers (2)

alexponomarenko
alexponomarenko

Reputation: 57

In controller:

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

In model (do not send any attributes to to_csv method):

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

Upvotes: 2

Alireza
Alireza

Reputation: 2691

@users is an array of users, and you are trying to call to_csv method on the array. On the other hand the to_csv method is defined as a class method, meaning you need to invoke it on the class itself:

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

Upvotes: 1

Related Questions