im creating a rails app (basically a monolith). currently, im creating a new feature, “when i click some button, it download a sql script with db backup”.
i understand that i can execute this command “PGPASSWORD=password pg_dump -U pguser -h localhost db_name_development > /tmp/backup-test.sql” and i can get the backup, but when i execute the command on the terminal, nothing happends.
Also, i created a controller and a view with the feature, when i click on the download button, my browser downloads the file but instantly throws me an “network error” and stops the download.
is my code bad or something? im still learning.
Controller:
class BackupsController < ApplicationController
def download
dump_file = create_backup
send_file dump_file, type: 'application/sql', disposition: 'attachment', filename: File.basename(dump_file)
ensure
File.delete(dump_file) if dump_file && File.exist?(dump_file)
end
private
def create_backup
timestamp = Time.now.strftime('%Y%m%d%H%M%S')
dump_file = Rails.root.join('tmp', "backup-#{timestamp}.sql")
db_config = Rails.configuration.database_configuration[Rails.env]
db_username = 'postgres'
db_password = 'postgres'
db_name = 'yunex_sicc_development'
db_host = db_config['host'] || 'localhost'
command = "PGPASSWORD=#{db_password} pg_dump -F c -v -U #{db_username} -h #{db_host} #{db_name} -f #{dump_file}"
if system(command)
dump_file.to_s
else
raise "Backup failed"
end
end
end
View:
<div class="col-12 col-sm-6 text-center">
<%= link_to(download_backup_path, method: :get, class: 'btn btn-outline-primary py-2 w-100' ) do %>
<%= image_tag "adm_icon_download_db.svg", class: "img-fluid img-button" %>
download db.
<% end %>
</div>
routes.rb:
get 'backups/download', to: 'backups#download', as: 'download_backup'