[RUBY] [Rails] How to upload multiple images using Carrierwave

Target

ezgif.com-video-to-gif.gif

Development environment

・ Ruby: 2.5.7 Rails: 5.2.4 ・ Vagrant: 2.2.7 -VirtualBox: 6.1 ・ OS: macOS Catalina

Premise

The following has been implemented.

Slim introduction -Login function implementationImplementation of posting function

Implementation

1. Introduce Gem

Gemfile


gem 'carrierwave'
gem 'mini_magick'

gem 'mini_magick' ➡︎ Allows you to change the size of the image when uploading.

Terminal


$ bundle

2. Create an image setting file

Terminal


$ rails g uploader image

ʻThe following file is created in app / uploaders / image_uploader.rb`. The setting method will be explained later.

uploaders/image_uploader.rb


class ImageUploader < CarrierWave::Uploader::Base
  # 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 be mounted:
  def store_dir
    "uploads/#{model.class.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(*args)
  #   # For Rails 3.1+ asset pipeline compatibility:
  #   # ActionController::Base.helpers.asset_path("fallback/" + [version_name, "default.png "].compact.join('_'))
  #
  #   "/images/fallback/" + [version_name, "default.png "].compact.join('_')
  # end

  # Process files as they are uploaded:
  # process scale: [200, 300]
  #
  # def scale(width, height)
  #   # do something
  # end

  # 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 allowed to be uploaded.
  # For images you might use something like this:
  # def extension_whitelist
  #   %w(jpg jpeg gif png)
  # end

  # Override the filename of the uploaded files:
  # Avoid using model.id or version_name here, see uploader/store.rb for details.
  # def filename
  #   "something.jpg " if original_filename
  # end
end

3. Add column

Terminal


$ rails g migration AddImagesToBooks images:json

Terminal


$ rails db:migrate

schema.rb


create_table "books", force: :cascade do |t|
  t.integer "user_id"
  t.string "title"
  t.text "body"
  t.datetime "created_at", null: false
  t.datetime "updated_at", null: false
  t.json "images"
end

4. Edit the model

book.rb


#Postscript
mount_uploaders :images, ImageUploader

5. Edit controller

Add {images []} to the strong parameter so that it can be saved as an array in the column.

books_controller.rb


def book_params
  params.require(:book).permit(:title, :body, { images: [] })
end

6. Edit the view

** ① Create an image submission form **

By adding multiple: true, you can select multiple images.

slim:books/~.html.slim


= f.file_field :images, multiple: true
br

** ② Display the image **

Arrange the ʻimages column with" 5. Edit controller ", and since there are multiple images in it, turn it with ʻeach to take it out.

** * The image will not be displayed unless .to_s is added. ** **

books/~html.slim


td
  - book.images.each do |image|
    = image_tag image.to_s

About settings

1. Image size setting

ʻInclude CarrierWave :: MiniMagick` is added, and the size setting is described below it.

** ① process resize_to_fill ** (recommended) Crop from the specified position ('Center') at the specified size (100, 100) from the original image without maintaining the aspect ratio.

uploaders/image_uploader.rb


class ImageUploader < CarrierWave::Uploader::Base
  include CarrierWave::MiniMagick
  process resize_to_fill: [100, 100, 'Center']
end

スクリーンショット 2020-06-06 9.59.35.png

process resize_to_fit You can maintain the aspect ratio and resize the width up to 300px and the height up to 200px.

uploaders/image_uploader.rb


class ImageUploader < CarrierWave::Uploader::Base
  include CarrierWave::MiniMagick
  process resize_to_fit: [100, 100]
end

スクリーンショット 2020-06-06 10.00.23.png

2. Extension restrictions

Uncomment lines 38-40 of ʻimage_uploader.rb`. By default, you cannot upload if the extension is other than jpg, jpeg, gif, png.

uploaders/image_uploader.rb


class ImageUploader < CarrierWave::Uploader::Base
  def extension_whitelist
    %w(jpg jpeg gif png)
  end
end

Recommended Posts

[Rails] How to upload multiple images using Carrierwave
[Rails] How to upload images using Carrierwave
[Rails] How to upload images to AWS S3 using Carrierwave and fog-aws
CarrierWave Upload multiple images
[Rails] How to delete images uploaded by carrierwave (using devise)
Multiple image upload function using Rails Carrierwave
[Rails] How to upload images to AWS S3 using refile and refile-s3
Upload multiple images easily with rails rails + carrierwave + cloudinary
[rails] How to post images
[Rails] Save images using carrierwave
How to download images from AWS S3 (rails, carrierwave)
[Ruby on Rails] How to use CarrierWave
How to implement image posting using rails
[Rails] How to handle data using enum
[rails6.0.0] How to save images using Active Storage in wizard format
How to write Rails
How to implement a slideshow using slick in Rails (one by one & multiple by one)
[Rails] How to create a graph using lazy_high_charts
How to uninstall Rails
How to link images using FactoryBot Active Storage
[Ruby on Rails] Upload multiple images with refile
How to post images on Heroku + CarrierWave + S3
[Rails 6] Two methods to import multiple images at once using CarrierWave / (1) Input with initial seed data / (2) Import with CSV
[Rails] How to search by multiple values ​​with LIKE
[Rails 6] Add images to seed files (using Active Storage)
Rails learning How to implement search function using ActiveModel
[Rails] How to install a decorator using gem draper
How to handle uploaded images
[Rails] How to use enum
[Rails] How to install devise
How to minimize Java images
[Rails] How to use enum
How to read rails routes
How to use rails join
How to terminate rails server
How to write Rails validation
How to write Rails seed
[Rails] How to use validation
[Rails] How to disable turbolinks
[Rails] How to use authenticate_user!
[Rails] How to use "kaminari"
[Rails] How to implement scraping
[Rails] How to make seed
How to write Rails routing
[Rails] How to install simple_calendar
[Rails] How to install reCAPTCHA
[Rails] How to use Scope
How to authorize using graphql-ruby
How to implement a circular profile image in Rails using CarrierWave and R Magick
How to test including images when using ActiveStorage and Faker
How to set environment variables when using Payjp with Rails
[Rails API + Vue] Upload and display images using Active Storage
Prevent operations! How to securely update Rails manually using transactions
How to set and describe environment variables using Rails zsh
How to deploy jQuery in your Rails app using Webpacker
[Rails] How to use gem "devise"
How to deploy jQuery on Rails
[Rails] How to install Font Awesome
[Rails] How to use flash messages
[rails] How to display db information
[Rails] How to write in Japanese