Table of contents
1.
Introduction
2.
Creating the model for file uploading
3.
Class methods of files in ruby 
4.
Instance methods of files in ruby 
5.
Frequently Asked Questions
6.
Key Takeaways
Last Updated: Mar 27, 2024

File uploading with Ruby on Rails

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

A server-side web application framework is Ruby on rails or rails, written in programming language ruby under the MIT License. It provides a default structure for a database for a website. While making websites, we want our users to upload the files on our site. This can be made easy by using ruby on rails. We will try to make a simple and small ruby on the rails project which will teach about file uploading.

For starting with creating the model, we need to make a basic structure of rail application.

rails new testfile

We need to install gem files before starting application development.

gem install carrierwave
gem install bootstrap-sass

We will add the two gems displayed below in gemfile at the bottom and run the following command in the console.

bundle install

Output-

Creating the model for file uploading

With two strings as ‘name’ and ‘attachment’, we need to create a model as shown below −

rails g model introduction name:string attachment:string

For creating database migration we will run the following command-

rake db:migrate

We will then generate the controller by running the below command-

rails g controller Introductions index new create destroy

Now our basic setup is ready. Now we will create an uploader which is provided by carrierwave gem. It tells how to handle files to carrierwave. 

For creating an uploader, use this command -

rails g uploader attachment

Now open the introduction model, which is placed at app/models/introduction.rb and call the uploader as shown below -

class Introduction < ActiveRecord::Base
   mount_uploader :attachment, AttachmentUploader # Tells rails to use this uploader for this model.
   validates :name, presence: true # Make sure the owner's name is present.
end
You can also try this code with Online Ruby Compiler
Run Code

Now we will modify config/routes.db before working on the controller in the following way-

CarrierWaveExample::Application.routes.draw do
   resources :introductions, only: [:index, :new, :create, :destroy]
   root "introductions#index"
end
You can also try this code with Online Ruby Compiler
Run Code

Now we will work with the controller by editing it as shown below-

class IntroductionsController < ApplicationController
   def index
      @introductions = Introduction.all
   end
   
   def new
      @introduction = Introduction.new
   end
   
   def create
      @introduction = Introduction.new(introduction_params)
      
      if @introduction.save
         redirect_to introductions_path, notice: "The introduction #{@introduction.name} has been uploaded."
      else
         render "new"
      end
      
   end
   
   def destroy
      @introduction = Introduction.find(params[:id])
      @introduction.destroy
      redirect_to introductions_path, notice: "The introduction #{@introduction.name} has been deleted."
   end
   
   private
      def introduction_params
      params.require(:introduction).permit(:name, :attachment)
   end
   
end
You can also try this code with Online Ruby Compiler
Run Code

Let's add bootstrap implementation in css file-app/assets/stylesheets/introductions.css.scss

@import "bootstrap";
You can also try this code with Online Ruby Compiler
Run Code

Now open up app/views/layouts/application.html.erb and add codes as shown below −

<!DOCTYPE html>
<html>
   
   <head>
      <title>Coding Ninjas</title>
      <%= stylesheet_link_tag "application", media: "all", "data-turbolinks-track" => true %>
      <%= javascript_include_tag "application", "data-turbolinks-track" => true %>
      <%= csrf_meta_tags %>
   </head>
   
   <body>
      <div class = "container" style = "padding-top:20px;">
         <%= yield %>
      </div>
   </body>


</html>

For setting up the index view we will write this code -

<% if !flash[:notice].blank? %>
   <div class = "alert alert-info">
      <%= flash[:notice] %>
   </div>
<% end %>


<br />


<%= link_to "New Introduction", new_introduction_path, class: "btn btn-primary" %>
<br />
<br />


<table class = "table table-bordered table-striped">
   <thead>.
      <tr>
         <th>Name</th>
         <th>Download Link</th>
         <th> </th>
      </tr>
   </thead>
   
   <tbody>
      <% @introductions.each do |introduction| %>
         
         <tr>
            <td><%= introduction.name %></td>
            <td><%= link_to "Download Introduction", introduction.attachment_url %></td>
            <td><%= button_to "Delete", introduction, method: :delete, class: "btn btn-danger", confirm: "Are you sure that you wish to delete #{introduction.name}?" %></td>
         </tr>
         
      <% end %>
   </tbody>
   
</table>

Now we will add our form code in new.html.erb file -

<% if !@introduction.errors.empty? %>
   <div class = "alert alert-error">
      
      <ul>
         <% @introduction.errors.full_messages.each do |msg| %>
            <li><%= msg %></li>
         <% end %>
      </ul>
      
   </div>
<% end %>


<div class = "well">
   <%= form_for @introduction, html: { multipart: true } do |f| %>
      <%= f.label :name %>
      <%= f.text_field :name %>
      <%= f.label :attachment %>
      <%= f.file_field :attachment %>
      <%= f.submit "Save", class: "btn btn-primary" %>
   <% end %>
</div>

Now we will open our browser. After that, we will type http://localhost:3000 to see the output.

Output-

We will now define a file type constraint that means all types of files are allowed or accepted. for this, we will modify the app/uploaders/attachment_uploader.rb file by adding the following Code-

class AttachmentUploader < CarrierWave::Uploader::Base
   storage :file
   
   def store_dir
      "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
   end
   
   def extension_white_list
      %w(pdf doc htm html docx)
   end
end
You can also try this code with Online Ruby Compiler
Run Code

Output-

Now we will go to http://localhost:3000 again, and will find an error message on giving the wrong format input file.

Class methods of files in ruby 

Class methods 

Descriptions

File::atime( path) Returns the time when the path was last accessed.
File::chown( owner, group, path...) The owner and the group of the specified file are changed. 
File::blockdev?( path) if path is a block device it return true value.
File::chardev?( path) if path is a character device it returns true value.
File::ctime( path) the last node change time is returned for path.
File::dirname( path) Without the final filename, the directory portion of the path is returned.
File::exist?( path) If the path exist it returns true value.
File::link( old, new) It creates a hard link for the file named old.
File::readable?( path) If the path is readable this returns true value.
File::rename( old, new) It changes the name of the file from old to new.

 

Instance methods of files in ruby 

Instance methods

Description 

f.atime Returns the time when f was last accessed.
f.chmode( mode) Permission mode of f is changed
f.chown( owner, group) Here owner and group of f is changed
f.ctime the last inode change time for f id returned.
f.flock( op) Calls flock(2), and here op maybe 0 or the File class constants LOCK_EX, LOCK_NB, LOCK_SH, and LOCK_UN  or a logical.
f.lstat It is the same as a stat, except information on symbolic links is returned here, not the files pointed.
f.mtime Returns the time when f was last modified.
f.path The pathname used to create the file is returned.
f.reopen( path[, mode = "r"]) This method helps to reopen a file.
f.truncate( len) This method truncates f to len bytes.

 

Frequently Asked Questions

1.How can we install ruby on rails?

  • First of all, install ruby on your device from https://rubyinstaller.org/, and the version should be above 2.2.2. After installing ruby, check the version on the command prompt of ruby by typing ruby -v.
  • Then check the version of the gem by typing gem --version.
  • Now install rails on your device by typing the command gem install rails.
  • Finally, check the rails version by using the rails -v command.

2.How does ruby on rails organize application programming?

It uses the model–view–controller (MVC) pattern. We use MVC to develop user interfaces as it is a software design pattern that divides the related program logic into three interconnected elements. This is done to differentiate internal information representations from the user's information presented to and accepted.

Key Takeaways

In this blog, we learned file uploading in ruby on rails. Don't come to a halt here. Check out our Ruby vs Python: What are the differences and how do they matter to you? | Coding Ninjas Blog. Can you also check out the Ruby and Ruby on Rails: How do they differ? | Coding Ninjas Blog blogs? Check out more blogs here more blogs

 

Happy Learning!

Live masterclass