Ruby on Rails File Uploading - Ruby on Rails

How can the site visitors upload a file on the server?

This requirement is easy on Rails. Let us see this through a simple and small Rails project.

First, we will create a new Rails application called testfile. Let's create the basic structure of the application by using simple rails command.

Before starting application development, we should install gem files as shown below −

Open up your gemfile and add the following two gems at the bottom as shown in the following image −

Gem file

After adding gems in the gem file, we need to run the following command on the console −

How to create the Model?

Let us create a model with two strings as name and attachment as shown below −

We need to create the database migration as shown below −

We need to generate the controller as shown below −

We have the basic structure set up now. Now we need to create an uploader. An Uploader came from carrierwave gem and it tells to carrierwave how to handle the files. In short, it contained all file processing functionalities. Run the command to create an uploader as shown below

Now open the resume model and call the uploader as shown below. Resume model has placed at app/models/resume.rb −

Before working on controller, we need to modify our config/routes.db as shown below −

Lets us edit the controller as shown below.

Let's add bootstrap implementation in css file.css file could be in app/assets/stylesheets/resumes.css.scss

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

Now we need to set up index views as shown below −

Now, lets edit new.html.erb and add our form code.

Now start the server and visit http://localhost:3000. It will produce a screen similar to as follows −

Output

One last thing we need to do is filter the list of allowed filetypes. For that we need add simple code as shown below at app/uploaders/attachment_uploader.rb

Now start the server and visit http://localhost:3000. Now input a wrong format; it will generate a wrong message as shown below −

Wrong output

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

Ruby on Rails Topics