Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Practice Problems
  • Python
  • C
  • C++
  • Java
  • Courses
  • Machine Learning
  • DevOps
  • Web Development
  • System Design
  • Aptitude
  • Projects
Open In App
Next Article:
How to create API in Ruby on Rails?
Next article icon

How to Upload Files in Ruby on Rails?

Last Updated : 21 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

Table of Content

  • Prerequisites
  • Approach
  • Steps to Upload a File
  • Conclusion
  • FAQs related to How to Upload Files in Ruby on Rails?

Prerequisites

  1. 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.
  2. Active Storage: Familiarity with Rails' Active Storage framework for handling file uploads and attachments.
  3. Forms Basics: Knowledge of how to create and process forms in Rails.
  4. Routing: Basic understanding of how routing works in Rails, especially how actions like new and create are mapped to URLs.
  5. 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.

  1. The form is created using the 'form_with' helper, where users can enter a title and select a file to upload.
  2. 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 App
Create a Rails App

Step 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 Model
Create a Model

Here, 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 database
Migrate Database

Step 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,

  1. Shrine
  2. Carrierwave
  3. Dragonfly
  4. Paperclip
  5. Refile

Active Storage is widely used and recommended. Install Active Storage by running,

rails active_storage:install rails db:migrate

Use Active Storage
Active Storage

This 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 Code
Model Code

This line indicates that each instance of the 'Folder' model can have one file attached to it.

Step 5: Create a Form to Upload Files

Next, create a form in your FoldersController to allow users to upload files. Generate the controller using,

rails generate controller Folders

Generate Controller
Generate Controller

Now, 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.


Next Article
How to create API in Ruby on Rails?

M

mukeshprajtjp2
Improve
Article Tags :
  • Ruby
  • RubyonRails

Similar Reads

  • How to Set Cookie in Ruby on Rails?
    Cookies are small pieces of data that are sent from a website and stored on the user's computer by the user's web browser. They are commonly used for session management, user authentication, personalization, and tracking. In Ruby on Rails, you can use the 'cookies' object to set, read, and delete co
    3 min read
  • How to Upload Files in JavaScript?
    We upload files using JavaScript, for this we have to capture form elements, gather information from FormData for easier file uploads, intercept submission events, and utilize Fetch API for asynchronous server requests, for enhanced user experience and efficient data handling. ApproachProject Setup:
    1 min read
  • How to create API in Ruby on Rails?
    Building APIs with Ruby on Rails: A Step-by-Step GuideRuby on Rails (Rails) is a popular framework for web development, known for its convention over configuration approach. It also excels in creating robust and maintainable APIs (Application Programming Interfaces). APIs act as intermediaries, allo
    3 min read
  • How to create table in Ruby on Rails?
    In Ruby on Rails, creating tables involves using migrations, which are a powerful mechanism for managing database schema changes. Here's a detailed breakdown of the process: 1. Database Setup (Optional): While APIs can function without databases, many Rails applications use them for data persistence
    3 min read
  • How to Upload File in Python-Flask
    File uploading is a typical task in web apps. Taking care of file upload in Flask is simple all we need is to have an HTML form with the encryption set to multipart/form information to publish the file into the URL. The server-side flask script brings the file from the request object utilizing the r
    2 min read
  • Ruby on Rails - How to Send Emails?
    Email communication is a must-have function for those who want their web application to keep up with the current trend. The Action Mailer Framework of Ruby on Rails helps to make the tasks of sending emails easier. This article focuses on discussing sending emails using Ruby on Rails. Table of Conte
    11 min read
  • How to Add Image in Ruby on Rails?
    In Ruby on Rails, there are several ways to add images to your application. In this article, we will see one of the common methods which is using an assets pipeline. Steps on How to Create a ProjectStep 1: Create a demo project using the command below. It will create a project named 'myapp' in the c
    2 min read
  • How to upload a file in PHP ?
    In this article, we will learn how to upload a file using PHP. Let us first understand some basic configurations. Approach: In your "php.ini" file, search for the "file_uploads" parameter and set it to "On" as mentioned below. file_uploads = On In the "index.html" file, the enctype must be multipart
    3 min read
  • How to Set File Path in Ruby?
    In Ruby, setting and working with file paths is a common task, whether you're reading from or writing to files. Ruby provides several ways to work with file paths, offering both simplicity and flexibility. This guide will explain how to set a file path in Ruby, covering basic usage and best practice
    4 min read
  • How to create model in Ruby on Rails?
    In Ruby on Rails, models are like the organizers of your data. They handle interactions with your database. Think of them as the brains of your application, responsible for managing and manipulating data. They represent the structure and behavior of the information your app works with. So, whenever
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences