LoginSignup
23
21

More than 5 years have passed since last update.

Rails + cloudinary + carrier wave 画像アップロードアプリのテスト

Last updated at Posted at 2018-06-30

環境

ruby 2.5
rails 5系
github
heroku

準備作業

cd ~/Projects/_rails
mkdir test_cloudinary
cd test_cloudinary
bundle init
echo -e "ruby '2.5.0'\ngem 'rails'" >> Gemfile
bundle install --path vendor/bundle --jobs=4
bundle exec rails new -B .

#GemfileがコンフリクトするのでyでOverwrite
y
Gemfile
#gem 'sqlite3'
gem 'sqlite3', group: [:development, :test]
gem 'pg', group: :production
echo -e "\ngem 'carrierwave'\ngem 'cloudinary'\ngem 'bootstrap-sass'" >> Gemfile

bundle
echo -e "\n/vendor/bundle\n/.envrc\n/public/uploads/tmp/\n/public/uploads/micropost/image/" >> .gitignore
git add .
git commit -m "first commit"

Githubでリポジトリを作成してくる
リポジトリ名は「test_cloudinary」

git remote add origin https://github.com/hogemax/test_cloudinary.git
git push -u origin master                                           

構築作業

アップローダーファイルの作成

bundle exec rails g uploader Image
app/uploaders/image_uploader.rb
  include Cloudinary::CarrierWave

  process :convert => 'png' # 画像の保存形式
  process :tags => ['image'] # 保存時に添付されるタグ(管理しやすいように適宜変更しましょう)

  process :resize_to_limit => [700, 700] # 任意でリサイズの制限

  # 保存する画像の種類をサイズ別に設定
  version :standard do
    process :resize_to_fill => [100, 150, :north]
  end

  version :thumb do
    process :resize_to_fit => [50, 50]
  end

  # 「storage :file」 が有効になっているとCloudinaryに画像アップロードできない ↓

  # Choose what kind of storage to use for this uploader:
  #storage :file
  # storage :fog

How to upload images to folders with CarrierWave
( ※ コメ欄のコードがGoodJob)

# アップロードした画像ファイルを任意のフォルダに保存する場合は
# 下記のように任意のフォルダ名を指定できる 例:「local_test_cloudinary」

  def public_id
    return "local_test_cloudinary/" + Cloudinary::Utils.random_public_id;
  end

フォルダの自動生成機能を利用するにはCloudinaryのセッティングページからAuto-create folders:Enabledにしておく必要がある Cloudinary | Settings - Upload


本番ではCloudinary使うけど開発ではローカルに保存する設定、の場合

Rails.envとかで切り分けの設定しとく

if Rails.env.production?
    include Cloudinary::CarrierWave
    # 本番用設定を書く
else
    include CarrierWave::RMagick
    # 開発・テスト用設定を書く
end

ちなみに、上記のように開発環境でRMagickGemを利用する場合、(インストール&Gem追加 されてなければ)imagemagickのインストールとGem(Gemfile)追加作業を済ませておく

# 「imagemagick」はhomebrewでインストール

# インストールされているか確認
brew list | grep imagemagick

# homebrewでimagemagickを(ver6系で)インストール
brew install imagemagick@6
brew link --force imagemagick@6

# gemの追加
echo -e "gem 'rmagick'" >> Gemfile
bundle

bundle install "rmagick" でインストールができない


投稿処理(Microposts)の作成

bundle exec rails g scaffold Microposts name:string image:string
bundle exec rails db:migrate

Uploaderファイルを関連付け

app/models/micropost.rb
  mount_uploader :image, ImageUploader

cloudinary設定ファイルの用意

cloudinary.ymlファイルのダウンロード(多分、ログインが必要)
ファイルはconfig配下に置く。

ダウンロードフォルダから直接コピーするコマンド
# 現在位置の確認
pwd
# ***/***/***/test_cloudinary

# プロジェクトディレクトリ(test_cloudinary)内にいる想定で
cp $HOME/Downloads/cloudinary.yml config/cloudinary.yml

環境変数設定

※ Gitにあげない場合はこの項目は読み飛ばす。

事前にdirenvを使えるようにしておく。

Githubにコミットする場合はコミット前にcloudinary.ymlファイル内の
APIキーなどを環境変数に置き換えておく。(そのままリポジトリにあげちゃうとマズイので。)

direnv edit .
.envrc
#cloudinaryAPI認証用
export CLOUDINARY_CLOUD_NAME="xxxxxxxxxx"
export CLOUDINARY_API_KEY="xxxxxxxxxxxxx"
export CLOUDINARY_API_SECRET="xxxxxxxxxxxxx"

で、cloudinary.ymlファイルの内容も置き換え。

config/cloudinary.yml
---
development:
  cloud_name: ENV['CLOUDINARY_CLOUD_NAME']
  api_key: ENV['CLOUDINARY_API_KEY']
  api_secret: ENV['CLOUDINARY_API_SECRET']
  enhance_image_tag: true
  static_image_support: false
production:
  cloud_name: ENV['CLOUDINARY_CLOUD_NAME']
  api_key: ENV['CLOUDINARY_API_KEY']
  api_secret: ENV['CLOUDINARY_API_SECRET']
  enhance_image_tag: true
  static_image_support: true
test:
  cloud_name: ENV['CLOUDINARY_CLOUD_NAME']
  api_key: ENV['CLOUDINARY_API_KEY']
  api_secret: ENV['CLOUDINARY_API_SECRET']
  enhance_image_tag: true
  static_image_support: false

Developer solution overview | Cloudinary

各viewファイルの修正

app/views/microposts/_form.html.erb

  <div class="field">
    <%= form.label :image %>
    <%= image_tag(micropost.image_url(:thumb), :width => 80, :height => 80) %>
    <%= form.file_field :image %>
  </div>
app/views/microposts/index.html.erb
<!-- ↓ これは消す -->
<!--        <td><%= micropost.image %></td> -->

<!-- ↓ こっちを適用(残す) -->
        <td><%= cl_image_tag(micropost.image_url(:thumb), :alt => micropost.name) %></td>
app/views/microposts/show.html.erb
<% if @micropost.image? %>
<p>
  <strong>Image:</strong>
  <!-- 画像表示 --> 
  <%= image_tag(@micropost.image_url, :alt => @micropost.name) %>
</p>
<p>
  <!-- id(URL)確認用 -->
  <%= @micropost.image_url.to_str %>
</p>
<% end %>

strong paramater を確認。
(おそらくデフォルトで以下内容が入力されてると思う)

app/controllers/microposts_controller.rb
    def micropost_params
      params.require(:micropost).permit(:name, :image)
    end

その他

ルーティング設定

config/routes.rb
   root 'microposts#index'

bootstrap(CSS)の反映(やらなくてもいいよ)

vim app/assets/stylesheets/custom.css.scss
app/assets/stylesheets/custom.css.scss
@import "bootstrap-sprockets";
@import "bootstrap";

Githubにアップ

開発で動作確認できたらGitに(あげたい人は)あげる

git add .
git commit -m "Make Image Upload Function"
git push

アドオン(本番環境用)

設定ができていればherokuのaddon(cloudinary)は入れなくてもいいっぽい

Herokuにアップする

本番環境(Heroku)にプロジェクトを載せて動かしてみるとか。
作業は下記参考に
Herokuにプロジェクト載せてサービス公開

既存のサービスに機能追加として画像登録を追加する場合
(もうすでに一度Herokuにプロジェクトが上がっている場合は)

git push heroku master

でおk

 環境変数の登録

先ほど設定したCloudinary用の環境変数をHeroku側にコマンドで登録する。

heroku config:set CLOUDINARY_CLOUD_NAME=xxxxxxxxxx
heroku config:set CLOUDINARY_API_KEY=xxxxxxxxxx
heroku config:set CLOUDINARY_API_SECRET=xxxxxxxxxx

動作確認して見て正常にアップできていればおkでは

参考

CarrierWave integration | Cloudinary
Cloudinary + Carrierwave + Heroku + Railsでの画像を手軽に利用する方法
Using Cloudinary and CarrierWave for Rails Image Uploading
How to upload images to folders with CarrierWave ( ※ コメント欄のコードがGoodJobだった)
cloudinary_gem/samples at master · cloudinary/cloudinary_gem · GitHub
Ruby好き非エンジニアのブログ
Ckeditorの画像アップロードをCloudinaryに変更する
jQueryを使ったCloudinaryのダイレクトアップロード - KayaMemo
マイグレーションを使ったカラムの追加、削除、データ型の変更 [ 自分用メモ ]
Rails の Model 作成時に単数形・複数形の変換がおかしい場合の対処法
Rails4はattr_accessibleが使えない

23
21
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
23
21