carrierwaveメモ

carrierwaveuploader/carrierwave https://github.com/carrierwaveuploader/carrierwave

Gemfile

gem 'carrierwave'
gem 'mini_magick'

via console

bundle install --path vendor/bundle
rails g uploader Image
rails g migration add_image_to_photos image:string
rake db:migrate

app/models/photos.rb

class Photo < ActiveRecord::Base
  mount_uploader :image, ImageUploader
end

app/uploaders/image_uploader.rb

class ImageUploader < CarrierWave::Uploader::Base
  # include CarrierWave::RMagick # アップロード時にstack level too deepエラーがでるのでMiniMagickにした
  include CarrierWave::MiniMagick
  storage :file
  permissions 0666
  directory_permissions 0777
  def extension_white_list
    %w(jpg jpeg gif png)
  end
  version :thumb do
    process :resize_to_fill => [200,200]
  end
end

app/views/photos/_form.html

<%= form_for @photo, :html => {:multipart => true} do |f| %>
  <p>
    <label>My Images</label>
    <%= f.file_field :image %>
    <%= f.hidden_field :image_cache %>
  </p>
  <p>
    <label>
      <%= f.check_box :remove_image %>
      Remove Image
    </label>
  </p>
<% end %>

app/views/photos/show.html(に適当に追加)

    <%= image_tag(@photo.image_url) if @photo.image? %>

その他、strong parametersのpermitted parametersでハマったりして時間かかった。

app/uploaders/***_uploader.rbに設定書くだけで、画像のリサイズやfog経由でs3とかrackspaceに保存できるのが便利そう。