Search code examples
csvruby-on-rails-4rake

Rails: Creating a csv file in a rake task - can't access a classes database column_names


I am struggling to create a simple rake task which will generate a csv dump of the database table "baselines".

task :send_report => :environment do
  path = "tmp/"
  filename = 'data_' + Date.today.to_s + '.csv'
   Baseline.all.each do
    CSV.open(path + filename, "wb") do |csv|
      csv << Baseline.column_names
      Baseline.all.each do |p|
        csv << p.attributes.values_at(*column_names)
       end
     end
   end
 end

I am getting the error

       undefined local variable or method `column_names' for main:Object

I am completely unclear why this is....Baseline.column_names will work in the console, in a view etc etc.

Any thought would be appreciated.


Solution

  • You're specifying Baseline.column_names in the first case, but just column_names on your values_at call. That defaults to the main context where no such method exists. It must be called against a model.

    Make those two consistent, Baseline is required in both cases.