[Ruby] [Rails6] Two methods to input multiple images at once using CarrierWave / ① Input with seed initial data / ② Import with CSV

4 minute read

Although it is easy to input multiple text columns other than the above, it was difficult because only the image (image) column became nil, so here are two methods to input multiple image columns at once. I will.

environment

  • Ruby 2.6.5
  • Rails 6.0.3.2

① How to populate multiple image columns with seed initial data

In db/migrate/seed.rb,

seed.rb



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

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

=> [#<Post:0x00007fa6c66bc8e8
  id: 27,
  image: nil,
  park: "Yadoguchi Park",
  outline:
   "People who know Hodokubo know.",
  location: "10 minutes walk from Takahatafudo Station on the Keio Line toward Momokusa-en 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: ["#water play", "#athletic"]>,
 #<Post:0x00007fa6c7b48f28
  id: 28,
  image: nil,
  park: "Umegari Park",
  outline: "It is a park with both brightness and calm atmosphere.",
  location: "88-1 Hyakusa 881 Hyakusa 8",
  access: "Misawadai Elementary School Bus Stop, 3 minutes walk east",
  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 when only the URL is entered 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: Yadoguchi Park,
outline: Only people in Hodokubo know,
location: 1-20-14 Hokurokubo, Hino-shi, Tokyo
access: 5 minutes walk from Hokurokubo 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 do rails db:reset and then rails db:seed.

*Please check the file in advance to see if the image actually exists in /image/1/yatoguti.jpg.

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

② How to import multiple image columns with CSV

Since initial data input was successful with seed.rb, describe it in the same way in db/csv_dara/csv_data.csv and lib/tasks/import_csv.rake this time, 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, a small park right next to "Takahatafudo" in Hino City. Located on a hill in the housing complex, it is a place for children in the area to relax. There are swings, slides, horizontal bars, sandboxes, and there is a space where you can play freely. , 714-21 Takahata, Hino-shi, Tokyo, 5 minutes walk from Takahatafudo station, # slide # horizontal bar # swing # sandbox
File.open("#{Rails.root}/public/uploads/post/image/8/hohoemi.jpg"), Smile Park, concrete mounds are popular parks. A tunnel running vertically and horizontally inside the mountain, a climbing route with a clasp outside, and a wide slide and sandbox are integrated, so you can enjoy a little adventure. ,6, 2 31-Minamidaira, Hino City, 5 minutes east from Kitano Kaido Expressway Bus Stop, #Slide #Tanbar #Branco
File.open("#{Rails.root}/public/uploads/post/image/7/hodokubo.jpg"), Hokubo District Square, slightly sloped grassland and thickets. There are no playground equipment, but you can enjoy climbing trees, sliding grass, picking up acorns, etc. It's raw, so it's okay to hang out with barefoot. ,2-22 Hodogokubo, Hino City, 5 minutes east from Tama Animal Park Station on Keio Line, # lawn

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 could be done because it is the description that the initial input of seed was completed. 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. Originally I imported it without the image column, so there is no doubt that the image column is the problem.

Solution

CSV is different from the case of seed, because it is ** treated as a character string **, 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

Describe the image column of import_csv.rake,

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, a small park right next to "Takahatafudo" in Hino City. Located on a hill in the housing complex, it is a place for children in the area to relax. There are swings, slides, horizontal bars, sandboxes, and there is a space where you can play freely. , 714-21 Takahata, Hino-shi, Tokyo, 5 minutes walk from Takahatafudo station, # slide # horizontal bar # swing # sandbox
"public/uploads/post/image/8/hohoemi.jpg", Smile Park, concrete mound is a popular park. A tunnel running vertically and horizontally inside the mountain, a climbing route with a clasp outside, and a wide slide and sandbox are integrated, so you can enjoy a little adventure. ,6, 2 31-Minamidaira, Hino City, 5 minutes east from Kitano Kaido Expressway Bus Stop, #Slide #Tanbar #Branco
"public/uploads/post/image/8/hodokubo.jpg", Hokuroku district square, grassland and copse with a little slope. There are no playground equipment, but you can enjoy climbing trees, sliding grass, picking up acorns, etc. It's raw, so it's okay to hang out with barefoot. ,2-22 Hodogokubo, Hino City, 5 minutes east from Tama Animal Park Station on Keio Line, # lawn

At the time of seed, it failed to describe only the URL, but on the contrary, it is better to set the CSV data to only the URL **.With this, we were able to import multiple images all at once with CSV!

Tags: ,

Updated: