LoginSignup
78

More than 5 years have passed since last update.

CarrierWave 複数の画像をコード三行で一つのカラムに保存する

Last updated at Posted at 2017-04-13

RailsのCarrierWaveというgemを使って@article.imagesで複数画像を呼び出せるようにする方法です。
「CarrierWave 複数画像」調べると画像の情報を保持するためのImagesテーブルを作って、has_many :imagesとする方法が出てくる。

しかし、CarrierWaveバージョン1.0.0から複数画像は公式でサポートされていて、上記の方法よりかなり簡潔に実装することが可能になっているのでそれを紹介します。

20170323192211.png

CarrierWaveで一つのオブジェクト(レコード)に複数の画像を保存する

複数の画像をアップロードする方法だけにフォーカスするためにCarrierWave自体のセットアップ方法についてはここでは触れません。
そもそもCarrierWave使っていないよ。という方には「Rails 超お手軽な画像アップローダー CarrierWave の使い方」がわかりやすくておすすめです。

古いバージョンのCarrierWaveを使っている場合はgem 'carrierwave', '~> 1.0.0'でバージョンを1.0.0以上にしておいてください。

実装

Articlesテーブルにimagesカラムを作ってそこに複数の画像を保存するという例でサンプルコードを記述します。

Articlesテーブルにimagesカラムを追加

$ rails g migration add_images_to_articles images:json
$ rake db:migrate

ImageUploaderをimagesカラムにマウント

app/models/article.rb
class Article < ActiveRecord::Base
  mount_uploaders :images, ImageUploader
  # Rails5.0未満を使ってる場合は以下のコードも必要
  # serialize :images, JSON
end

画像アップロード用のフォームを作成

app/views/articles/show.html.erb
<%= form.file_field :images, multiple: true %>

strong parameters にimages追加

app/controllers/articles_controller.rb
params.require(:article).permit(:title, :body, {images: []})

以上です。

うまくいかない、カスタマイズが必要といった人は公式README.mdのMultiple file uploadsの項と画像の追加と削除の仕方に目を通すと幸せになれると思います!

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
78