1
1

More than 3 years have passed since last update.

CarrierWaveを使ってseeds.rbで画像を登録する

Last updated at Posted at 2021-05-31

経緯

初期データを登録する際に、画像も一緒に登録できるようにしました。
その過程を残しておきます。

手順1 gemのインストール

Gemfile
gem 'carrierwave'
$ bundle install 

手順2 アップローダーを作成する

ターミナル
$ rails g uploader image //imageは任意の名前

手順3 モデルのアソシエーション

user.rb
class User < ApplicationRecord
  mount_uploader :image, ImageUploader
end

手順4 登録したい画像を用意

publicフォルダ配下にimagesフォルダなどを作成し、その中に画像を格納する。

手順5 seeds.rbに記入しデータを作成

seeds.rb
User.create!(
  name: 'John', 
  age: '20', 
  hobby: 'walking', 
  image:File.open("./public/images/John.jpg")
)
ターミナル
$ rails db:seed

これで画像の登録ができました!

<コンソールやviewの表示などでエラーが出る際は下記参照>

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1