In my Rails application, I create a CSV file using CSV.open block in a model method.
class SomeModel
def self.write_csv
CSV.open("my_file_name.csv", "w") do |csv|
### inserts lines into the file ###
end
end
end
In my controller, I have an action that sends the file to a user input email address
def some_controller_method
SomeModel.write_csv
email = params[:email]
JobMailer.send_csv(email).deliver
end
In the JobMailer
, I directly refer to the file by file name because the CSV.open
block from SomeModel.write_csv
saves the file onto disk at the main directory.
def send_csv(email)
attachments['my_file_name.csv'] = {mime_type: 'text/csv', content: File.read(Rails.root.join('your_file.csv'))}
mail(to: email, subject: 'My subject', body: 'My body.')
end
Currently the app will rewrite over the file when a new request comes in, and I believe when I push to production on Heroku, it will automatically delete it after some time.
To recap:
Can this be done without saving it to disk? Is there a better way?
At the top of our controller let's import the built-in Rails csv library: And now we can format our controller to respond when CSV is requested. Rails uses the respond_to method to allow controller endpoints to respond to multiple formats. You will see a lot of endpoints that respond with HTML, JSON, and even XML.
Learn how to export records into CSV files using Ruby on Rails. Here are the steps. Add a controller and make sure you handle the csv request. Lets code it! # routes.rb ... resources :users, only: :index ...
First let's pull the data. We'll need to build a query and save the results to an instance variable. @leads = Leads.where (organization_id: current_user.organization_id) Next we have to convert the result of this query into the CSV format. At the top of our controller let's import the built-in Rails csv library:
To generate a CSV file, though, you probably still need to go to the database to get the data, which can also be slow. If you are making a large database call to start your CSV generation, then you can still use Rails and Enumerators to help speed up the start of the database load, and therefore the start of your CSV data stream.
You can use CSV#generate class method
class SomeModel
def self.generate_csv
CSV.generate do |csv|
### inserts lines into the file ###
end
end
end
def some_controller_method
csv = SomeModel.generate_csv
email = params[:email]
JobMailer.send_csv(email, csv).deliver
end
def send_csv(email, csv)
attachments['my_file_name.csv'] = {mime_type: 'text/csv', content: csv}
mail(to: email, subject: 'My subject', body: 'My body.')
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With