namespace :db do
desc 'Import data from a .sql file'
task :import_sql_data, [:file_path] do |task, args|
file_path = args[:file_path]
# Check if the file exists
unless File.exist?(file_path)
puts "Error: File '#{file_path}' does not exist"
exit
end
# Execute the SQL commands in the file
ActiveRecord::Base.connection.execute(File.read(file_path))
puts 'Data imported successfully!'
end
end
Run:
bundle exec rake db:import_sql_data[file_path]
Example:
bundle exec rake db:import_sql_data[db/my_data.sql]