Question

I am trying to write a rake task to drop a table and repopulate it from a csv. The intention is to obtain the data from another system on a schedule, and use a button in the admin interface of my rails application to import the new data. This new data will overwrite the old data in the table.

I am not exactly sure how to do this so am playing around with rake tasks. So far I can import the new data but I can't figure out how to drop the table first. My code so far is:

namespace :csvimportproducts do

  desc "Import Products CSV Data."
  task :import_products_csv_data => :environment do

    ActiveRecord::Migration.drop_table products

    require 'csv'
    csv_file_path = '/home/jay/workspace/db/import_tables/products.csv'
    CSV.foreach(csv_file_path) do |row|
      p = Product.create!({
          :product_id => row[0],
          :product_name => row[1],
        }
      )
    end
  end
end

At the moment I am storing the csv files locally but intend later to have it uploaded by the administrator as a csv file.

Any ideas? My error is:

rake aborted!                                                                                                                                                      
undefined local variable or method `products' for main:Object                                                                                                      
/lib/tasks/import_products_csv.rake:6:in `block (2 levels) in <top (required)>'                                                               
Tasks: TOP => csvimportproducts:import_products_csv_data
Était-ce utile?

La solution

Try by truncating the table by running a custom sql command:

namespace :csvimportproducts do

  desc "Import Products CSV Data."
  task :import_products_csv_data => :environment do

    ActiveRecord::Base.connection.execute("TRUNCATE TABLE products")

    require 'csv'
    csv_file_path = '/home/jay/workspace/db/import_tables/products.csv'
    CSV.foreach(csv_file_path) do |row|
      p = Product.create!({
          :product_id => row[0],
          :product_name => row[1],
        }
      )
    end
  end
end
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top