LoginSignup
4
4

More than 5 years have passed since last update.

画像アップロードCarrierwaveを導入する

Posted at

画像アップロードのGem Carrierwaveの導入方法を忘れちゃうので、手順をメモ。
今回は画像リサイズのためmini_magickも導入します

Gemfileを設定

それでは早速、下記Gemをインストールします。

Gemfile.
gem 'carrierwave'
gem 'mini_magick'

そして、「bundle install」。また「rails g uploader image」でアップローダーも作成します。

ターミナル.
bundle install
rails g uploader image //アップローダーを作成

app/uploaders/image_uploader.rb //ファイルが作成されます

画像をカラムがない場合は作成しましょう。今回はproductモデルに作成します。

ターミナル.
rails g migration add_image_to_product image:string
rake db:migrate

カラムができました。追加したモデルの「product.rb」を編集し
「image_uploader」をマウントする記述をします。

product.rb
class Product < ApplicationRecord
  mount_uploader :image, ImageUploader #記述を追加
end

先ほど作成した「image_uploader.rb」を編集して、MiniMagick経由で画像のリサイズを行えるようにします

app/uploaders/image_uploader.rb
include CarrierWave::MiniMagick
process resize_to_fit: [800, 800]
#上記追記。コメントアウトされてるところもあるので、それを解除でも可。

以上で導入はOKです。

参考

[参考]carrierwaveの使い方
[参考]CarrierWaveの使い方

4
4
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
4
4