How to Upload Files in Ruby on Rails?
Last Updated :
21 Aug, 2024
Uploading files in a web application is a common requirement, whether it's for user profile pictures, documents, or any other files. Ruby on Rails makes this task straightforward with its built-in tools. In this article, we'll walk through the steps to set up file uploads in a Rails app, from creating the project to displaying and downloading the uploaded files.
Prerequisites
- Ruby on Rails: Understanding of Rails models, controllers, views, and the MVC (Model-View-Controller) architecture. If Ruby on Rails is not already installed, Install Ruby on Rails on Windows or Linux or Install Ruby on Rails on macOS.
- Active Storage: Familiarity with Rails' Active Storage framework for handling file uploads and attachments.
- Forms Basics: Knowledge of how to create and process forms in Rails.
- Routing: Basic understanding of how routing works in Rails, especially how actions like new and create are mapped to URLs.
- Database Basics: Understanding of how Rails interacts with databases, including how models correspond to database tables.
Approach
In this example, we are using the direct form submission method to upload a file in a Ruby on Rails application.
- The form is created using the 'form_with' helper, where users can enter a title and select a file to upload.
- When the form is submitted, the file and title are sent to the server as part of the form data.
This method is straightforward to implement, especially for simple file upload needs. Other methods, such as AJAX file upload, chunked file upload, and direct-to-cloud storage upload, offer more advanced features like asynchronous uploading, handling large files, and offloading storage to cloud services. These approaches can be implemented to enhance user experience and scalability.
Steps to Upload a File
Step 1: Create a Rails App
First, you'll need to create a new Rails application. Open your terminal and run the below command,
rails new file_app
Create a Rails AppStep 2: Create a Model
To upload files, you'll need a model to store the file information. Let's create a model called 'Folder'. Make sure you are inside your project directory while executing the command.
rails generate model Folder title:string file:string
Create a ModelHere, the title will be a string to store the document's name, and the file will hold the uploaded file's path.
After running the command, migrate the database.
rails db:migrate
Migrate DatabaseStep 3: Use Active Storage
Rails has a built-in tool called Active Storage that makes file uploads easy. There are other useful gems and tools for file handling like,
- Shrine
- Carrierwave
- Dragonfly
- Paperclip
- Refile
Active Storage is widely used and recommended. Install Active Storage by running,
rails active_storage:install rails db:migrate
Active StorageThis will add tables to your database to store file uploads.
Step 4: Set Up the Model to Use Active Storage
Now, update the 'Folder' model to attach files using Active Storage. Open 'app/models/folder.rb' and modify it like this,
Model CodeThis line indicates that each instance of the 'Folder' model can have one file attached to it.
Next, create a form in your FoldersController to allow users to upload files. Generate the controller using,
rails generate controller Folders
Generate ControllerNow, add a 'new' action in 'app/controllers/folders_controller.rb'. This initializes a new, unsaved instance of the 'Folder' model and assigns it to the instance variable @folder.
In the same controller, add a 'create' action to save the uploaded file. The create action in the controller initializes a new 'Folder' with user-submitted parameters, attempts to save it, and either redirects to the document's show page with a success message or re-renders the new form if saving fails. The 'folder_params' method ensures that only permitted parameters are used.
Ruby
class FoldersController < ApplicationController
def new
@folder = Folder.new
end
def create
@folder = Folder.new(folder_params)
if @folder.save
redirect_to @folder, notice: 'File was successfully uploaded.'
else
render :new
end
end
private
def folder_params
params.require(:folder).permit(:title, :file)
end
end
Step 6: Create the View
Now, create a view to render the upload form. In 'app/views/folders/new.html.erb', add the following code,
HTML
<h1>Upload a New File</h1>
<%= form_with(model: @folder, local: true) do |form| %>
<div class="field">
<%= form.label :title %>
<%= form.text_field :title %>
</div>
<div class="field">
<%= form.label :file %>
<%= form.file_field :file %>
</div>
<div class="actions">
<%= form.submit 'Upload' %>
</div>
<% end %>
Step 7: Display Uploaded Files
To display the uploaded files, add a 'show' action in 'app/controllers/folders_controller.rb',
Ruby
def show
@folder = Folder.find(params[:id])
end
Then, create a view to show the document in 'app/views/folders/show.html.erb',
HTML
<h1><%= @folder.title %></h1>
<p>
<%= link_to 'Download file', rails_blob_path(@folder.file, disposition: "attachment") %>
</p>
Step 8: Add Routes
Finally, make sure to add routes for the new actions. In 'config/routes.rb', add: the following,
Rails.application.routes.draw do resources :folders, only: [:new, :create, :show] end
Step 9: Start the server
Start your Rails server using,
rails server
Visit 'http://localhost:3000/folders/new' in your browser to see the upload form. After uploading a file, you should be able to view and download it on the folder's show page.
Output
Conclusion
In conclusion, file uploading in Ruby on Rails is easy to set up and use. With Rails' built-in features, you can quickly add file upload functionality to your app. This method lets users upload files through simple forms and manages those files efficiently on the server. Rails makes handling file uploads straightforward, ensuring that you can focus on building your app without worrying about complex file management issues.