Uploading a Song on Ruby on Rails
Read Time: half dozen mins Languages:
If you are building a web application, you lot definitely will want to enable paradigm uploading. Paradigm uploading is an of import feature in modernistic-day applications, and images have been known to be useful in search engine optimization.
In this tutorial (which is the first role of the Rails Epitome Uploading series), I will testify you how to enable image uploading in your Rails awarding using CarrierWave. Information technology will be a simple application equally the focus is on the image uploading.
CarrierWave is a Ruby gem that provides a simple and extremely flexible way to upload files from Ruby-red applications. Yous need to have Track on your machine to follow along. To be sure, open upwards your terminal and enter the control beneath:
rail -v
That will bear witness you the version of Rails you have installed. For this tutorial I will exist using version iv.2.4, which you can install like so:
gem install track -v iv.2.iv
With that done, you are skilful to get.
Runway Awarding Setup
At present create a new Track project:
rails new mypets
Open up your Gemfile and add the following gems.
*Gemfile* ... gem 'carrierwave', '~> 0.10.0' gem 'mini_magick', '~> iv.3' ...
The first gem is for CarrierWave, and the 2nd jewel chosen mini_magick helps with the resizing of images in your Rails awarding. With that washed, run package install.
Generate a scaffold resource to add CarrierWave'south functionality. Run the following command from your terminal:
rails 1000 scaffold Pet name:cord description:text paradigm:cord
A scaffold in Rails is a full set up of model, database migration for that model, controller to dispense information technology, views to view and manipulate the data, and a test suite for each of the above.
Drift your database next:
rake db:migrate
Setting Upwards CarrierWave
You need to create an initializer for CarrierWave, which will be used for loading CarrierWave after loading ActiveRecord.
Navigate to config > initializers and create a file: carrier_wave.rb.
Paste the code below into it.
*config/initializers/carrier_wave.rb* crave 'carrierwave/orm/activerecord'
From your terminal, generate an uploader:
rails generate uploader Image
This will create a new directory called uploaders in the app folder and a file inside called image_uploader.rb
. The content of the file should await like this:
*app/uploaders/image_uploader.rb* # encoding: utf-8 class ImageUploader < CarrierWave::Uploader::Base of operations # Include RMagick or MiniMagick support: # include CarrierWave::RMagick # include CarrierWave::MiniMagick # Choose what kind of storage to use for this uploader: storage :file # storage :fog # Override the directory where uploaded files will be stored. # This is a sensible default for uploaders that are meant to exist mounted: def store_dir "uploads/#{model.grade.to_s.underscore}/#{mounted_as}/#{model.id}" end # Provide a default URL as a default if there hasn't been a file uploaded: # def default_url # # For Rails 3.1+ asset pipeline compatibility: # # ActionController::Base.helpers.asset_path("fallback/" + [version_name, "default.png"].compact.bring together('_')) # # "/images/fallback/" + [version_name, "default.png"].compact.join('_') # finish # Procedure files as they are uploaded: # procedure :scale => [200, 300] # # def scale(width, height) # # exercise something # stop # Create different versions of your uploaded files: # version :thumb do # process :resize_to_fit => [50, 50] # end # Add a white list of extensions which are immune to be uploaded. # For images you might employ something similar this: # def extension_white_list # %w(jpg jpeg gif png) # end # Override the filename of the uploaded files: # Avoid using model.id or version_name hither, see uploader/store.rb for details. # def filename # "something.jpg" if original_filename # end terminate
You can edit it to fit what you want. Let me have you through information technology.
Offset, uncomment the MiniMagick line. That should exist line seven.
... include CarrierWave::MiniMagick ...
You need this to generate unlike versions of an epitome. If you want to generate a thumbnail version of images uploaded, there is already a code form included in the image_uploader file for you lot. Uncomment the version code cake equally shown below:
... version :thumb do process :resize_to_fill => [50, l] end ...
You tin also add together unlike versions using the aforementioned format.
For the purpose of this tutorial, we will be saving to file and not fog. Fog is the Ruby cloud service library. I will show you how to put it into use in another part of this series. So go out your storage choice as it is.
For security purposes, certain files might pose a threat if allowed to be uploaded to the wrong location. CarrierWave allows you to specify a white-list of allowed extensions. You should see a method that looks similar what I have below, and so uncomment it.
... def extension_white_list %w(jpg jpeg gif png) end ...
It is time to mount your uploader. Navigate to your model and paste the code below.
*app/model/pet.rb* mount_uploader :image, ImageUploader
Go to your views and edit it to look like what I have below:
app/views/pets/_form.html.erbprohibited this pet from being saved:
- </ul> </div> </pre> Open up your concluding and offset your runway server: `rails s`. Point your browser to [https://localhost:3000/pets](http://localhost:3000/pets). You lot should exist able to add a new pet by inbound a name and clarification and uploading an image. The prototype does not become displayed after successful upload. Let me show you how to fix that. Navigate to your prove page where you are displaying the paradigm, and edit it to fit what I have beneath:
*app/views/pets/show.html.erb*This will display the thumbnail version of the prototype. CarrierWave makes information technology easy to remove a previously uploaded file on a mounted uploader with just a checkbox. I will evidence you how to do information technology. Open up your course file and make a little adjustment. Edit it to look similar this:Name:
Description:
Image:
|*app/views/pets/_form.html.erb*prohibited this pet from existence saved:
- </ul> </div> </pre> In the code to a higher place, we checked if there is already an image object. If in that location is, we display the image and the option to remove it, but if there is none, we display simply the field to upload the image. Navigate to your controller and add `:remove_image` to your params. Reload your edit page, tick the box, click on **Update Pet**, and the image will be removed. ### Validating Prototype Size There are different means of doing this. I volition show yous an easy and quick method. Open up your pet model and paste in the code below:
*app/model/pet.rb validates_processing_of :image validate :image_size_validation private def image_size_validation errors[:image] << "should be less than 500KB" if image.size > 0.5.megabytes endThis volition help ensure that no paradigm greater than 500KB gets uploaded to your Rails awarding. Get-go your rails server and check out what you have. ## Determination Now y'all know how to enable image uploading in your Rails application. You lot take as well learned how to validate the format and size, too as deleting an image. In the next function of this series, we volition await at how to use CarrierWave aslope Devise.
Did you find this post useful?
Source: https://code.tutsplus.com/tutorials/rails-image-upload-using-carrierwave-in-a-rails-app--cms-25183
0 Response to "Uploading a Song on Ruby on Rails"
Post a Comment