[Ruby] Implementation method that links multiple images to one post and posts at the same time

5 minute read

Introduction

I posted an article as a struggling memo to implement the function to post multiple images

Launch the app

$ rails _5.2.3_ new App name -d mysql
$ cd app name
$ bin/rails db:create

Introducing ##haml This time implementation will be done with haml, so we will introduce haml

Add the following to the gem file Don’t forget to do bundle install

gem'haml-rails'

Easy to create posting function

routes


Rails.application.routes.draw do
  root'products#index'
  resources :products, only: [:index, :new, :create]
end

controller


class ProductsController <ApplicationController
  def index
    @products = Product.includes(:images).order('created_at DESC')
  end

  def new
    @product = Product.new
    @product.images.new
  end

  def create
    @product = Product.new(product_params)
    if @product.save
      redirect_to root_path
    else
      render :new
    end
  end
  

  private

  def product_params
    params.require(:product).permit(:name, images_attributes: [:src])
  end

end

model and migration

product migration file

class CreateProducts <ActiveRecord::Migration[5.2]
  def change
    create_table :products do |t|
      t.string :name

      t.timestamps
    end
  end
end

image Migration file


 class CreateImages <ActiveRecord::Migration[5.2]
  def change
    create_table :images do |t|
      t.string :src
      t.references :product, foreign_key: true

      t.timestamps
    end
  end
end

products model


class Product <ApplicationRecord
  has_many :images
  accepts_nested_attributes_for :images, allow_destroy: true
end

image model


class Image <ApplicationRecord
  mount_uploader :src, ImageUploader
  belongs_to :product
end

image We will be uploading images with the model.

Add the following to the Gemfile and $ bundle install

gem'carrierwave'
gem'mini_magick'

create uploader

In the terminal run

$ rails g uploader image

Next, the image_uploader.rb file is generated, so edit the following

include CarrierWave::MiniMagick // Look for this description and uncomment it

process resize_to_fit: [100, 100] // Add this description

Finally edit haml and scss

haml/new



.lead
  =link_to "/products" do
    =image_tag "http://furima.tokyo/assets/logo-d3d78326971d78b06e3d6f0ba666d025a8ad681286b4d9e00e7dbe8673bcfd23.svg", class: "lead__img"
  
= form_with model: @product, local: true do |f|
  .input-field
    .input-field__contents
      .input-field__contents-image
        .input-field__contents-image__headline
          .headlabel
            Exhibition image
            %span.necessary
              Required
        %p.upload
          You can upload up to 5
        
    #image-box-1
          .item-num-0#image-box__container
            = f.fields_for :images do |i|
              .input-field__contents-image__drop__js-file
                .input-area
                  = i.file_field :src
    
      .input-field__contents-name
        .input-field__contents-image__headline
          .headlabel
            %label
              Product name
              %span.necessary
                Required
          .name-input
            = f.text_field :name, {class: "drop-input", placeholder: "up to 40 characters"}
    
    .input-field
      .input-field__contents
        .input-field__contents-price
          .sell
            = f.submit "Sell", class: "sellbtn", tabindex: "0"

new.scss



.lead {
  background-color: rgb(245, 245, 245);
  text-align: center;
  height: 128px;
  line-height: 10;
}
.input-field {
  background-color: rgb(245, 245, 245);
  width: 100%;
  .input-field__contents {
    left: 0;
    background-color: white;
    max-width: 800px;
    margin: 0 auto;
    padding: 40px;
    border-bottom: 1px solid hsl(0, 0%, 77%);
    height: 100%;
    .input-field__contents-image {
      width: 800px;
      border-bottom: rgb(204, 204, 204);
      .input-field__contents-image__headline{
        margin-top: 20px;
        margin-left: 5px;
      }
      .upload {
        margin-top: 16px;
        margin-left: 5px;
      }
  #image-box-1 {
        display: flex;
        height: 130px;
        width: 100%;
        margin-right: 0px;
        text-align: center;
        i{
          padding-top: 50px;
        }
        .item-num-0#image-box__container {
        background-color: rgb(245, 245, 245);
        height: 100%;
        width: 100%;
        border-width: 1px;
        border-style: dashed;
        border-color: rgb(204, 204, 204);
        border-image: initial;
        text-align: center;
        }
      }
    }
  }
  .drop-input {
    width: 60%;
    height: 50px;
    border-color: #cccccc;
    border-radius: 4px;
    border-style: solid;
    border-width: 1px;
    margin: 10px 10px 0 0;
  }
  .name-input{
    .drop-input{
      width: 100%;
      height: 50px;
      border-color: #cccccc;
      border-style: solid;
    }
  }
  .sell {
    text-align: center;
    display: grid;
    width: 50%;
    margin-left: 200px;
    .sellbtn {
      background-color: #3ccace;
      color: white;
      border-color: transparent;
      font-weight: 600;
      line-height: 3;
      cursor: pointer;
    }
  }
}

It is complete if the following is done.https://gyazo.com/a1d705516656f50c689abc7c18de5ec9

Post multiple images

Introducing jQuery

gem'jquery-rails'

Then do bundle install

Editing ###application.js

//= require rails-ujs
//= require activestorage
//= require jquery
//= require_tree.

edit new.haml


- # before editing
# image-box-1
 .item-num-0#image-box__container
  = f.fields_for :images do |i|
   .input-field__contents-image__drop__js-file
    .input-area
     = i.file_field :src
- # After editing

# image-box-1
 .item-num-0#image-box__container
  = f.fields_for :images do |i|
   .input-field__contents-image__drop__js-file
    .input-area
    = i.file_field :src, type:'file', name: "product[images_attributes][][name]", value:"", style: "display:none", id:"img-file"
    %label{for: "img-file"}
     %i.fas.fa-camera

Create and edit new.js to post multiple images

new.js


$(function(){
  //Create a box to store the data with the DataTransfer object
  var dataBox = new DataTransfer(); // Step ②
  //get file_field with querySelector
  var file_field = document.querySelector('input[type=file]')
  //Event fired when file is selected
  $('#img-file').change(function(){
    // Get the selected file object with prop
    var files = $('input[type=file]').prop('files')[0];
    $.each(this.files, function(i,file){
    //Read the File object specified by readAsDataURL of FileReader
    var fileReader = new FileReader();

    //Add file to DataTransfer object
    dataBox.items.add(file) // Step ②
    //Substitute the file list entered in the dataTransfer object in file_field
    file_field.files = dataBox.files // Step ②

    var num = $('.item-image').length + 1 + i // Step ②
    fileReader.readAsDataURL(file); // Step ②
     // Delete the drop box when the number of images exceeds 10
     if (num == 5){ // step ②
      $('#image-box__container').css('display','none')
     }
    //When loading is complete, store the URL of file in src
    fileReader.onloadend = function() {
      var src = fileReader.result
      var html = `<div class='item-image' data-image="${file.name}">
                    <div class=' item-image__content'>
                      <div class='item-image__content--icon'>
                        <img src=${src} width="150" height="90">
                      </div>
                    </div>
                    <div class='item-image__operetion'>
                      <div class='item-image__operetion--delete'>delete</div>
                    </div>
                  </div>`
     // Insert html before the image_box__container element
      $('#image-box__container').before(html);
      };
    // fileReader.readAsDataURL(file);
    // });
     //Change the class of image-box__container and change the size of the drop box with CSS.
     $('#image-box__container').attr('class', `item-num-${num}`)
    });
  });
    $(document).on("click",'.item-image__operetion--delete', function(){
      // Get the preview element
      var target_image = $(this).parent().parent()
      // remove preview
      target_image.remove();
      //Delete the file in the input tag
      file_field.val("")
    })
});

Edit #scss


.lead {
  background-color: rgb(245, 245, 245);
  text-align: center;
  height: 128px;
  line-height: 10;
}

.input-field {
  background-color: rgb(245, 245, 245);
  width: 100%;
  &__contents {
    left: 0;
    background-color: white;
    max-width: 800px;
    margin: 0 auto;
    padding: 40px;
    border-bottom: 1px solid hsl(0, 0%, 77%);
    height: 100%;
  }
  
  .input-field__contents-image {
    width: 800px;
    border-bottom: rgb(204, 204, 204);
    .input-field__contents-image__headline{
      font-weight: 600;
      margin-top: 20px;
      margin-left: 5px;
      .name-input {
        height: 54px;
        .option-input {
          display: block;
          width: 93%;
          border-color: #cccccc;
          height: 100%;
          border-radius: 4px;
          font-weight: bolder;
          padding: 0px 2px 1px;
          border-width: 1px;
        }
      }
    }
    .upload {
      margin-top: 16px;
      margin-left: 5px;
    }
# image-box-1 {
      display: flex;
      height: 130px;
      width: 100%;
      margin-right: 0px;
      text-align: center;
      i{
        padding-top: 50px;
        cursor: pointer;
      }
      .item-num-0#image-box__container {
      background-color: rgb(245, 245, 245);
      height: 100%;
      width: 100%;
      border-width: 1px;
      border-style: dashed;
      border-color: rgb(204, 204, 204);
      border-image: initial;
      text-align: center;
      }
      .item-num-1{
        background-color: rgb(245, 245, 245);
      height: 100%;
      width: 100%;
      border-width: 1px;
      border-style: dashed;
      border-color: rgb(204, 204, 204);
      border-image: initial;
      text-align: center;
      }
      .item-num-2{
        background-color: rgb(245, 245, 245);
        height: 100%;
        width: 100%;
        border-width: 1px;
        border-style: dashed;
        border-color: rgb(204, 204, 204);
        border-image: initial;
        text-align: center;
      }
      .item-num-3{
        background-color: rgb(245, 245, 245);
        height: 100%;
        width: 100%;
        border-width: 1px;border-style: dashed;
        border-color: rgb(204, 204, 204);
        border-image: initial;
        text-align: center;
      }
      .item-num-4{
        background-color: rgb(245, 245, 245);
      height: 100%;
      width: 100%;
      border-width: 1px;
      border-style: dashed;
      border-color: rgb(204, 204, 204);
      border-image: initial;
      text-align: center;

      }
      .item-num-5{
        background-color: rgb(245, 245, 245);
        height: 100%;
        width: 100%;
        border-width: 1px;
        border-style: dashed;
        border-color: rgb(204, 204, 204);
        border-image: initial;
        text-align: center;
      }  
    }
    //レビュー表示のCSS
    .item-image{
      height: 130px;
      width: 160px;
      border: 1px solid #eee;
      margin-right: 10px;
      .item-image__content{
        padding-top: 10px;
        .item-image__content--icon{
        }
      }
      .item-image__operetion{
        .item-image__operetion--delete{
          color: #00b0ff;
          cursor: pointer;
          padding-top: 5px;
         text-align: center;

        }
      }
    }
  }

  .text-area {
    border-radius: 4px;
    font-size: 16px;
    padding: 13px 16px;
    border-color: #cccccc;
    margin-top: 30px;
    
  }
  .drop-input {
    width: 100%;
    height: 50px;
    border-color: #cccccc;
    border-radius: 4px;
    border-style: solid;
    border-width: 1px;
    margin: 10px 10px 0 0;
    ::placeholder {
      padding: 20px;
      font-weight: inherit;
    } 
  }
 
  .headlabel {
    margin-top: 30px;
    .necessary {
      background-color: #3ccace;
      color: white;
      padding: 2px 4px;
      font-size: 14px;
      margin-left: 3px;
      cursor: pointer;
      border-radius: 2px;
     }
  }
  .sell {
    text-align: center;
    display: grid;
    width: 50%;
    margin-left: 200px;
    .sellbtn {
      background-color: #3ccace;
      color: white;
      font-size: 20px;
      min-height: 48px;
      padding: 0 24px;
      border-color: transparent;
      border-radius: 2px;
      font-weight: 600;
      line-height: 3;
    }
  }
}

これで一通りは完成 動作を確認 https://gyazo.com/372657130a2696e1865c02fdd6e9e303

編集や削除の機能は別記事で続きを書きます