[Rails 6] Two methods to import multiple images at once using CarrierWave / (1) Input with initial seed data / (2) Import with CSV

It is easy to insert multiple other text columns, but I had a hard time because all of the image columns became nil, so here are two methods to input multiple image columns at once. I will.

environment

(1) How to input multiple image columns with the initial data of seed

In db / migrate / seed.rb,

seed.rb



Post.create!(image: /public/uploads/post/image/1/yatoguti.jpg,
park:Yatoguchi Park,
outline:Everyone in Hodokubo knows,
location:1-20-14 Hodokubo, Hino-shi, Tokyo,
access:5 minutes walk from Hodokubo Monorail Station)

And then rails db: reset, then rails db: seed,

=> [#<Post:0x00007fa6c66bc8e8
  id: 27,
  image: nil,
  park: "Yatoguchi Park",
  outline:
   "Everyone in Hodokubo knows.",
  location: "10 minutes walk from Takahatafudo Station on the Keio Line toward Mogusaen Station",
  access: "1024 Takahata, Hino City",
  created_at: Sun, 02 Aug 2020 14:38:30 JST +09:00,
  updated_at: Sun, 02 Aug 2020 14:38:30 JST +09:00,
  likes_count: nil,
  tag_list: ["#Playing in the water", "#Athletic"]>,
 #<Post:0x00007fa6c7b48f28
  id: 28,
  image: nil,
  park: "Rainmaking Park",
  outline: "It is a park that has both brightness and a calm atmosphere.",
  location: "8 of 881 Mogusa, Hino City",
  access: "3 minutes walk east from Misawadai Elementary School bus stop",
  created_at: Sun, 02 Aug 2020 14:38:30 JST +09:00,
  updated_at: Sun, 02 Aug 2020 14:38:30 JST +09:00,
  likes_count: nil,
:...skipping...

In this way, the ** image column becomes nil ** if only the URL is described directly.

Solution

Rewrite the description of the image URL in the image column as follows.

seed.rb



Post.create!(image: File.open("#{Rails.root}/public/uploads/post/image/1/yatoguti.jpg "),
park:Yatoguchi Park,
outline:Everyone in Hodokubo knows,
location:1-20-14 Hodokubo, Hino-shi, Tokyo,
access:5 minutes walk from Hodokubo Monorail Station)

The description of the image column,

Post.create!(image: /public/uploads/post/image/1/yatoguti.jpg,

not,

Post.create!(image: File.open("#{Rails.root}/public/uploads/post/image/1/yatoguti.jpg "),

Change to. Then rails db: reset and then rails db: seed.

With this, the seed initial data can be input all at once!

(2) How to import multiple image columns in CSV format

Since the initial data input was successful in seed.rb, this time, write in the same way with db / csv_dara / csv_data.csv and lib / tasks / import_csv.rake, and try CSV import.

csv_data.csv


image,park,outline,location,access,tag_list
File.open("#{Rails.root}/public/uploads/post/image/6/ajisai.jpg "),Fuyo Park,It is a small park right next to "Takahatafudo" in Hino City. Located on a hill in the housing complex, it is a place of relaxation for local children. There are swings, slides, horizontal bars, sandboxes, and there is also a space where you can play freely.,714 Takahata, Hino City, Tokyo-21,5 minutes walk from Takahatafudo Station,#slide#Horizontal bar#Swing#Sandbox
File.open("#{Rails.root}/public/uploads/post/image/8/hohoemi.jpg "),Hohoemi Park,The concrete mound is a popular park. A tunnel that runs vertically and horizontally in the small mountain, a mountain climbing route with a clasp on the outside, and a wide slide and sandbox are integrated, so you can enjoy a little adventure.,2-31-6, Minamidaira, Hino-shi,5 minutes east from the Kitano Kaidoguchi bus stop,#slide#Horizontal bar#Swing
File.open("#{Rails.root}/public/uploads/post/image/7/hodokubo.jpg "),Hodokubo District Square,Slightly sloping grasslands and thickets. There are no playground equipment, but you can enjoy climbing trees, sliding grass, and picking up acorns. It's barefoot, so it's okay to go barefoot.,3-22-2 Hodokubo, Hino City,5 minutes walk east from Tama Animal Park Station on the Keio Line,#grass

lib/tasks/import_csv.rake


require 'csv'

namespace :import_csv do

  desc "Task to import CSV data of post table"
  task posts: :environment do
    path = File.join Rails.root, "db/csv_data/csv_data.csv"
    list = []
    CSV.foreach(path, headers: true) do |row|
      list << {
          image: row ["image"],
          park: row["park"],
          outline: row["outline"],
          location: row["location"],
          access: row["access"],
          tag_list: row["tag_list"]
      }
    end
    puts "Start import process"
     Post.create!(list)
      puts "Import complete!!"
  end

end


I thought that CSV import would be possible because it was described that the seed was initially input. Then ...

rake aborted!
CSV::MalformedCSVError: Illegal quoting in line 2.
/Users/sekishinya/Desktop/park_app/lib/tasks/import_csv.rake:11:in `block (2 levels) in <main>'
Tasks: TOP => import_csv:posts
(See full trace by running task with --trace)

Cannot import due to an error. Since I originally imported without the image column, there is no doubt that the image column is the problem.

Solution

Unlike the case of seed, CSV is treated as ** all character strings **, so the description is different.

Therefore, rewrite lib / tasks / import_csv.rake and db / csv_dara / csv_data.csv as follows.

import_csv.rake


require 'csv'

namespace :import_csv do

  desc "Task to import CSV data of post table"
  task posts: :environment do
    path = File.join Rails.root, "db/csv_data/csv_data.csv"
    list = []
    CSV.foreach(path, headers: true) do |row|
      list << {
          image: File.open("#{Rails.root}/#{row["image"]}"),
          park: row["park"],
          outline: row["outline"],
          location: row["location"],
          access: row["access"],
          tag_list: row["tag_list"]
      }
    end
    puts "Start import process"
     Post.create!(list)
      puts "Import complete!!"
  end

end

ʻImport_csv.rake` image column description,

image: row ["image"],

not,

image: File.open("#{Rails.root}/#{row["image"]}"),

Change to.

Then, change the image column of csv_data.csv as follows.

csv_data.csv


image,park,outline,location,access,tag_list
"public/uploads/post/image/8/fuyou.jpg ",Fuyo Park,It is a small park right next to "Takahatafudo" in Hino City. Located on a hill in the housing complex, it is a place of relaxation for local children. There are swings, slides, horizontal bars, sandboxes, and there is also a space where you can play freely.,714 Takahata, Hino City, Tokyo-21,5 minutes walk from Takahatafudo Station,#slide#Horizontal bar#Swing#Sandbox
"public/uploads/post/image/8/hohoemi.jpg ",Hohoemi Park,The concrete mound is a popular park. A tunnel that runs vertically and horizontally in the small mountain, a mountain climbing route with a clasp on the outside, and a wide slide and sandbox are integrated, so you can enjoy a little adventure.,2-31-6, Minamidaira, Hino-shi,5 minutes east from the Kitano Kaidoguchi bus stop,#slide#Horizontal bar#Swing
"public/uploads/post/image/8/hodokubo.jpg ",Hodokubo District Square,Slightly sloping grasslands and thickets. There are no playground equipment, but you can enjoy climbing trees, sliding grass, and picking up acorns. It's barefoot, so it's okay to go barefoot.,3-22-2 Hodokubo, Hino City,5 minutes walk east from Tama Animal Park Station on the Keio Line,#grass

At the time of seed, it failed to describe only the URL, but ** conversely, it is better to write only the URL ** for CSV data.

With this, we succeeded in importing multiple images at once even in CSV!

Recommended Posts

[Rails 6] Two methods to import multiple images at once using CarrierWave / (1) Input with initial seed data / (2) Import with CSV
How to input multiple images at once using rake task
[Rails] How to upload multiple images using Carrierwave
Rails6: Input the initial data of ActionText using seed
[Rails] Initial data creation with seed
Initial data input with [Rails] seed_fu!
[Rails] How to upload images using Carrierwave
Script to make yaml from CSV to put initial data in Rails with Fixtures
Upload multiple images easily with rails rails + carrierwave + cloudinary
Create an EC site with Rails5 ⑥ ~ seed data input ~
[Rails 6] Add images to seed files (using Active Storage)
[Rails] How to delete images uploaded by carrierwave (using devise)
[Rails] Save images using carrierwave
[Rails] How to upload images to AWS S3 using Carrierwave and fog-aws