[RUBY] [Rails 6.0] About batch saving of multiple records

Introduction

Since we have implemented the order management function in the personal application, we will output the method of batch saving of multiple records learned at that time.

Reference material

In creating this article, I have greatly referred to the following articles. I'm really thankful to you. [Rails 5] Procedure for batch registration of models [Rails 6] Batch registration using form_with 1.2. Implementation of batch registration form

Product

商品登録.png

Register only products with checkboxes checked 商品保存.png

商品一覧.png

Prerequisites

Product model

Column Type
name string
price integer
unit string
availability boolean

models/product.rb


class Product < ApplicationRecord

  with_options presence: true do
   validates :name
   validates :unit
   validates :price, numericality: {only_integer: true, greater_than_or_equal_to: 0 }
   validates :availability, inclusion: { in: [true, false] }
  end

end

policy

  1. Create a collection model for saving multiple products at once
  2. Describe the process for batch registration on the controller
  3. Create a form that allows you to register multiple products at once on the view screen

1. Create a collection model for saving multiple products at once

Create a form directory in the models directory, and create a ProductCollection model and a Base model in it.

models/form/product_collection


class Form::ProductCollection < Form::Base
  FORM_COUNT = 10 #Here, specify the number of registration forms you want to create
  attr_accessor :products 

  def initialize(attributes = {})
    super attributes
    self.products = FORM_COUNT.times.map { Product.new() } unless self.products.present?
  end
  
  def products_attributes=(attributes)
    self.products = attributes.map { |_, v| Product.new(v) }
  end

  def save
    Product.transaction do
      self.products.map do |product|
        if product.availability #Only the products for which the check box is checked here are saved.
          product.save
        end
      end
    end
      return true
    rescue => e
      return false
  end
end

models/form/base.rb


class Form::Base
  include ActiveModel::Model
  include ActiveModel::Callbacks
  include ActiveModel::Validations
  include ActiveModel::Validations::Callbacks

end

2. Instance creation and data processing with the controller

controllers/products_controller.rb



class ProductsController < ApplicationController
  
  def new
    @form = Form::ProductCollection.new
  end

  def create
    @form = Form::ProductCollection.new(product_collection_params)
    if @form.save
      redirect_to products_path, notice: "I registered the product"
    else
      flash.now[:alert] = "Product registration failed"
      render :new
    end

  end

  private
  
    def product_collection_params
        params.require(:form_product_collection)
        .permit(products_attributes: [:name, :price, :unit, :availability])
    end
    
end

@form = Form :: ProductCollection.new will instantiate the model you just created. Strong parameters are received in products_attributes.

3. Create a form that allows you to register multiple products at once on the view screen

ruby:views/products/new.html.haml


= form_with model: @form, url: products_path, method: :post, local: true do |form|
  %table
    %thread
      %tr
        %th registration
        %th product name
        %th selling price (yen)
        %th ordering unit
  %tbody
    = form.fields_for :products do |f|
      %tr
        %td.text-center
          = f.check_box :availability
        %td
          = f.text_field :name
        %td
          = f.text_field :price
        %td
          = f.text_field :unit
  = form.submit "Bulk registration"
  = link_to "Return", :back

I am creating a form that can be registered multiple times using form_with and fields_for.

Now you can save all at once.

Finally

Thank you for visiting. If you have any mistakes, please point them out.

Recommended Posts

[Rails 6.0] About batch saving of multiple records
[Rails] List instances of multiple models
[Rails] About implementation of like function
About Rails 6
About Rails routing
[Rails] Implementation of batch processing using whenever (gem)
[Rails] About ActiveJob ,!
About Rails controller
About RSpec (Rails)
[Rails] About migration files
[Rails 6] About main gems
About disconnect () of HttpURLConnection
About rails application server
[Rails] Introduction of PAY.JP
About rails kaminari pagination
About rails version specification
About DI of Spring ①
About DI of Spring ②
MEMO about Rails 6 series
Rails Tutorial/Significance of Indexing
[Rails] About Slim notation
Registration of multiple WebMvcConfigurers
About form. ○○ of form_with
About @Accessors of Lombok
[rails] About devise defaults
Rails: About partial templates
About rails strong parameters
[Beginner] About Rails Session
[Rails] Put the same restrictions on multiple pieces of information
About regular execution of rake task of rails application on heroku
A note about the seed function of Ruby on Rails
Existing records disappear when building a model of has_one (rails)