LoginSignup
1
4

More than 5 years have passed since last update.

CarrierWaveの使い方【Gem】

Posted at

CarrierWaveの使い方を調べたのでまとめる。この記事ではアップロードから表示までをやっている。

imagemagickが必要なのでインストールする。
$ brew install imagemagick

新しいプロジェクトを作成。
$ rails new uploader
$ cd uploader

Gemfileに追記。

Gemfile
gem 'carrierwave'

$ bundle install

scaffoldを作成。
$ rails g scaffold user name:string password:string

$ rails g uploader Avatar

データベースを作成、マイグレーション。
$ rails g migration add_avatar_to_users avatar:string
$ rake db:create db:migrate

以下を追記。

app/models/user.rb
class User < ActiveRecord::Base
  mount_uploader :avatar, AvatarUploader
end

アップロード画面。

app/views/users/_form.html.erb
  <div class="field">
  <%= form.label :avatar %><br>
  <%= form.file_field :avatar %>
  </div>

画像を表示。

app/views/users/show.html.erb
<p>
  <strong>Image:</strong>
  <%= image_tag @user.avatar %>
</p>

サーバーを立ち上げる。
$ rails s

アップロードと表示が可能になっている。

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