0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Rails】Carrierwaveを導入する

Posted at

タイトルと本文のみの投稿ができるブログアプリに
写真の投稿機能を追加した時の、Carrierwaveを導入する
手順に付いてまとめました。

1. Gemfileファイルを編集する

Gemfile
gem 'carrierwave'
gem 'mini_magick'
ターミナル
% bundle install

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

ターミナル
rails g uploader image

実行後、app/uploaders 下に image_uploader.rbが作成されます。

3. アップローダーをマウントする

app/models/message.rb
class Message < ApplicationRecord
  belongs_to :group
  belongs_to :user
  belongs_to :heven

  validates :content, presence: true, unless: :image?

  mount_uploader :image, ImageUploader  ⬅️ この1行
end

4. 画像のリサイズを可能にする

include CarrierWave::MiniMagick のコメントアウトを外し、
任意の行に**process resize_to_fit: [800, 800]**と追記。
これにより、縦横比を維持したまま、縦横を800px以内にリサイズ可能になります。

app/uploaders/image_uploader.rb
class ImageUploader < CarrierWave::Uploader::Base
  # Include RMagick or MiniMagick support:
  # include CarrierWave::RMagick
  include CarrierWave::MiniMagick  ⬅️ 有効化

# 〜省略〜

  process resize_to_fit: [600, 600]  ⬅️ 追記

# 〜省略〜
end

以上で画像のアップロードの準備ができました。

ご覧いただきありがとうございました。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?