kurusaki 開発ブログ

プログラミングや会社のこと、写真、自転車のことなど書いてます

画像アップローダ CarrierWaveの使い方

Railsのアプリでで画像をアップロードするGemのCarrierWaveの使い方をまとめてみます。

CarrierWaveはこれ↓
https://github.com/carrierwaveuploader/carrierwave

Gemfile

Gemfileにcarrierwaveとrmagickを追加する。

gem 'carrierwave'
gem 'rmagick'

bundle install

$ bundle install --path vendor/bundle

uploaderを作成

$ rails g uploader image

最後のimageの部分がクラス名に付くのでアップロードする画像毎に、
アップロード先のディレクトリやその他の設定を変更したい場合は名前を変えて指定する。
上記の場合は、app/uploaders/image_uploader.rbが作成される。

uploaderクラスの設定例

# encoding: utf-8

class ActionImageUploader < CarrierWave::Uploader::Base

  # Include RMagick or MiniMagick support:
  include CarrierWave::RMagick
  # include CarrierWave::MiniMagick

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

  # Override the directory where uploaded files will be stored.
  # This is a sensible default for uploaders that are meant to be mounted:
  def store_dir
    "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
  end

  # Provide a default URL as a default if there hasn't been a file uploaded:
  # def default_url
  #   # For Rails 3.1+ asset pipeline compatibility:
  #   # ActionController::Base.helpers.asset_path("fallback/" + [version_name, "default.png"].compact.join('_'))
  #
  #   "/images/fallback/" + [version_name, "default.png"].compact.join('_')
  # end

  # Process files as they are uploaded:
  # process :scale => [200, 300]
  #
  def scale(width, height)
     # do something
  end

  # Create different versions of your uploaded files:
  version :thumb do
    process :resize_to_fit => [100, 100]
  end

  # Add a white list of extensions which are allowed to be uploaded.
  # For images you might use something like this:
  def extension_white_list
    %w(jpg jpeg gif png)
  end

  # Override the filename of the uploaded files:
  # Avoid using model.id or version_name here, see uploader/store.rb for details.
  # def filename
  #   "something.jpg" if original_filename
  # end
  def filename
    time = Time.now
    name = time.strftime('%Y%m%d%H%M%S') + '.jpg'
    name.downcase
  end

end

モデルにuploaderクラスを指定

class Hoge < ActiveRecord::Base

  mount_uploader :picture, ImageUploader

end

_form.html.hamlの修正

  .form-group
    = f.label :picture, class: 'control-label'
    .controls
      
      - if @hoge.picture?
        = image_tag @hoge.picture.url
        %br
      = f.file_field :picture, class: 'form-control'
      = f.hidden_field :picture_cache
      -if @hoge.persisted? && @hoge.picture?
        = f.check_box :remove_picture
        画像を削除
{/code}

_show.html.hamlの修正

%p
  %strong= model_class.human_attribute_name(:picture) + ':'
  %br
  - if @hoge.picture?
    =image_tag @hoge.picture.url

サムネイルの表示

          -if button_action.picture?
            = image_tag button_action.picture_url(:thumb).to_s

Controllerを修正

対象のカラムに合わせてキャッシュ用の:xxxx_cache, 削除用の:remove_xxxxを追加する

    def hoge_params
      params.require(:hoge).permit(:title, :picture, :picture_cache, :remove_picture)
    end