LoginSignup
56
54

More than 5 years have passed since last update.

Rails gem CarrierWave を利用してファイルをアップロードする

Posted at

ファイルアップロード機能をお手軽に作成出来る gem CarrierWave のインストール・設定を行う。

GitHub リポジトリ CarrierWave
(https://github.com/carrierwaveuploader/carrierwave)

※ インストールの方法から、利用方法までは上記 GitHub に全てまとまっています。

前提

バージョン
Ruby 2.1.1
Rails 4.2.0
CarrierWave 0.10.0

1. インストール

Gemfile へ CarrierWave を追記

Gemfile
gem 'carrierwave'

Gemfile をインストール。
( rails プロジェクト内に閉じた状態で gem をインストールしたいため --path オプションを利用 )

$ bundle install --path vendor/bundle

2. uploader クラス作成

CarrierWave では uploader というジェネレータが提供されるので、任意の名前でクラスを作成。
以下では image という名前で uploader クラスを生成。

$ rails g uploader image

3. モデルクラスへ作成した uploader を設定

store という店舗情報を扱うモデルクラスへ、image という string 型のカラムを追加する想定で説明。
カラム名は必ず、作成した uploader と同じ名前にする。

マイグレーションを作成 & 実行。

$ rails g migration addImageToStores image:string
$ rake db:migrate

store モデルへ uploader を設定。

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

4. ビューの修正

form へファイル選択ボックスを追加。
また、バリデーションでエラーが発生し、フォームが再表示された場合もアップロードされたファイルが保持されるように カラム名_cache という hidden フィールドを用意しておく。

app/views/stores/_form.html.erb
<div class="field">
  <%= image_tag @store.image.url if @store.image? %>
  <%= f.label :image %><br>
  <%= f.file_field :image %>
  <%= f.hidden_field :image_cache %>
</div>

※ Rails4 から、form 内に file_field を含む場合、自動的に multipart オプションをつけてくれるので、form_for ヘルパー等の修正は不要。

画像を表示する。

app/views/stores/show.html.erb
<p>
  <strong>Image:</strong>
  <%= image_tag @photo.image.url %>
</p>

5. コントローラの修正

strong params へビューで追加した image と image_cache を追記する。

app/controllers/stores_controller.rb
params.require(:store).permit(:name, :address, :image, :image_cache)

おまけ

uploader クラスで、ファイルアップロード時の処理を制御。
ジェネレータで作成したクラスを見ると、よく使われる設定がコメント書きされているので、それをもとに変更するとよいかも。

app/uploaders/image_uploader.rb

# JPEG 形式に変換して保存
process convert: "jpg" 

# 拡張子 jpg jpeg gif png のみ許可
def extension_white_list
  %w(jpg jpeg gif png)
end

# ファイル名は original.jpg で保存 (jpeg変換しているので拡張子は固定)
def filename
  "original.jpg" if original_filename
end

以上。

56
54
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
56
54