LoginSignup
132
136

More than 5 years have passed since last update.

railsでcarrierwaveを使って画像をアップロード、表示

Posted at

私的メモ

carriwaveを使ってファイルをアップロード、そして表示させるミニマム手法

前提

scaffoldで基盤が作られている。
carrierwave用のカラムもimage:stringとしてついでに作っておく。

Gemfile
>rails g scaffold user name:string body:text image:string
.処理
.
.
>rake db:migrate

Gemインストール

Gemfile
gem 'carrierwave'

bundle installを忘れずに

terminal
>bundle install

おまじない

もし、Gemをインストールしたあとrails consoleを使用して「uninitialized constant Event::EventImageUploader」とエラーがでるならおまじないが必要

module WorkspaceのクラスApplication内に記述

config.autoload_paths += Dir[Rails.root.join('app', 'uploaders')]

application.rb
module Workspace
  class Application < Rails::Application
.省略
.
.
#おまじない開始
    config.autoload_paths += Dir[Rails.root.join('app', 'uploaders')]
#おまじない終わり
  end
end

carriewaveの設定ファイル?の作成

terminal
>rails g uploader images

app/uploaders/images_uploader.rbでファイルの中身はclass ImagesUploader生成される

DBテーブルへ画像保存用のカラムを追加

ファイルパスを保存するカラムを追加する。
(今回は予めscaffoldでimage:stringを定義していたので下記の作業は飛ばしてOK。)

terminal
>rails g migration add_image_to_user image:string
.
.
>rake db:migrate

モデルのとの紐づけ

mount_uploader :carrierwave用に作ったカラム名, carrierwaveの設定ファイルのクラス名

上の一行を関連づけるモデルに追加。
今回はscaffoldでuserモデルを作成していたのでuser.rbに記述する

user.rb
class User < ActiveRecord::Base
    mount_uploader :image, ImagesUploader
end

ファイルのアップロード

たぶんscaffoldで自動で作られた:image用のフォームはf.text_field :imageになので、f.file_fieldに変更する。

_form.html.erb
<%= f.label :image %>
<%= f.file_field :image %>
.
.

画像の表示

画像の表示はviewにimage_tag user.image.to_sで表示させる

index.html.erb
 <% @users.each do |user| %>
      <tr>
        <td><%= image_tag user.image.to_s %></td>
      </tr>
 <% end %>
132
136
1

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
132
136