2
4

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 5 years have passed since last update.

【最速シリーズ】最速でCarrierwaveで画像アップロードまで作る

Last updated at Posted at 2016-05-03

画像を投稿出来るめっちゃ便利なCarrierWave
https://github.com/carrierwaveuploader/carrierwave

今日は最速で画像アップロードまで作ります

①作りたいModel名でscaffold & Migrate

まず、Modelを用意します。
今回はviewとかをいちいち作ってると最速にならないので面倒なのでscaffoldしちゃいます

$ rails g scaffold Image content:string
$ rake db:migrate

②formを変更

f.text_fieldの部分をf.file_fieldに変更

app/views/images/_form.html.erb
<%= form_for(@image) do |f| %>
  <% if @image.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@image.errors.count, "error") %> prohibited this image from being saved:</h2>

      <ul>
      <% @image.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= f.label :content %><br>
    <%= f.file_field :content %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

③Gemをインストール

gemfileに追加してbundle install

Gemfile
gem 'carrierwave'
gem 'rmagick'

$ bundle install

④uploaderをgenerate

Uploaderをgenerateします(とりあえず、引数はImageでOK)

$ rails g uploader Image

⑤作成したファイルにこれをコピペ

app/uploaders/image_uploader.rb
# encoding: utf-8

class ImageUploader < CarrierWave::Uploader::Base

  storage :file

  include CarrierWave::RMagick

  process :resize_to_limit => [700, 700]
  process :convert => 'jpg'

  version :thumb do
    process :resize_to_limit => [300, 300]
  end

  def store_dir
    "uploads/photos/"
  end

  def extension_white_list
    %w(jpg jpeg gif png)
  end

  def filename
    Time.now.strftime('%Y%m%d%H%M%S') + original_filename + '.jpg' if original_filename.present?
  end

end

⑥【完成】Modelにマウント

app/models/image.rb
class Image < ActiveRecord::Base

  mount_uploader :content, ImageUploader

  ....

end

### これで完成!

おまけ:作成したUploaderに何かメソッド追加したいとき

なにかメソッドを追加したいときには、process :method_nameで定義すると読み込まれます!

app/uploaders/image_uploader.rb
# encoding: utf-8

class ImageUploader < CarrierWave::Uploader::Base

  ...

  process :hogehoge

  def hogehoge
    p 'うまくいったはず'
  end 

  ...

end

## おまけ:carrierwaveでexif情報をとりたい時
http://qiita.com/funao/items/ceb7106b4a1ef7e23122

最速シリーズ

【最速シリーズ】最速でdeviseでfacebookログインまで作る
http://qiita.com/funao/items/6337589eef8f94b6eae0

2
4
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
2
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?