2

I want to generate CSV file after user creates his account, so I created after_save filter in User Model, but I'm getting errors.

Here is my code:

    after_save :to_csv

    def to_csv(options = {})
    require 'csv'
    CSV.generate(options) do |csv|
        csv << self.column_names//also tried User.column_names
        csv << self.attributes.values_at(*column_names)
    end
    end

but when User is created I get error:

     undefined local variable or method `column_names' for #<User:0x326f778>       
     app/models/user.rb:52:in `block in to_csv'
     app/models/user.rb:50:in `to_csv'
     app/controllers/users_controller.rb:27:in `create'

Why I'm getting this ? I'm using this railscast - http://railscasts.com/episodes/362-exporting-csv-and-excel.

Samiron
  • 5,169
  • 2
  • 28
  • 55
MID
  • 1,815
  • 4
  • 29
  • 40

3 Answers3

4

column_names is a method on the class. You're calling it on the instance. If you really want column_names then use self.class.column_names.

Ryan Bigg
  • 106,965
  • 23
  • 235
  • 261
  • can you suggest where is my generated file ? Also tried to generated by calling `CSV.open("myfile.csv", "w") do |csv| ` – MID Sep 03 '12 at 07:47
3

Try self.attributes.keys which return columns

Amar
  • 6,874
  • 4
  • 25
  • 23
0

Am bit late int he game but here it is

self.attribute_names

does the job for me.

Bart C
  • 1,509
  • 2
  • 16
  • 17