LoginSignup
31
46

More than 5 years have passed since last update.

carrierwaveの使い方

Posted at

1. CarrierWaveのインストール

gem "carrierwave"
ターミナル
$ bundle install

2. アップローダーの生成

ターミナル
$ rails g uploader Image
create  app/uploaders/image_uploader.rb

image_uploader.rbでは、ファイルの保存方法(デフォルトはファイル)、保存パス、ファイルのサイズ、拡張子やファイル名の変換などが変更できる

(ActiveRecordを使って、アップロードしたファイルの情報を保存する方法)

例:productモデルにファイル情報を持つ場合

public/uploads/products配下に保存

Modelにimageフィールド(アップローダーで付けた名前と同じにしなければならない)を追加

ターミナル
$ rails g migration add_image_to_product image:string
$ rake db:migrate

モデルファイルを開き、アップローダーへのマウントする記述を追加

app/models/product.rb
class Product < ActiveRecord::Base
  mount_uploader :image, ImageUploader
end

新規/編集フォームに画像アップロードの入力フィールドを追加

hidden属性でimage_cacheは、画像を指定したけれども、バリデーションエラーなどにより保存が失敗した場合の画面再表示時などに、画像情報をキャッシュしておくための領域

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

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

  <div class="field">
    <%= f.label :name %><br>
    <%= f.text_field :name %>
  </div>
  <div class="field">
    <%= f.label :price %><br>
    <%= f.number_field :price %>
  </div>
  <!-- 追加箇所 開始 -->
  <div class="field">
    <% if @product.image? %>
      <div class="thumbnail">
        <%= image_tag @product.image.url %>
      </div>
    <% end %><br>
    <%= f.label :image %><br>
    <%= f.file_field :image %>
    <%= f.hidden_field :image_cache %>
  </div>
  <div class="field">
    <!-- 既存レコード(DBに保存されている)かつ、画像が存在する場合 -->
    <% if @product.persisted? && @product.image? %>
      <label>
        <%= f.check_box :remove_image %>
        画像を削除
      </label>
    <% end %>
  </div>
  <!-- 追加箇所 終了 -->
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

ファイルの属性を更新できるようにするために、StrongParametersに:image, :image_cache, :remove_imageを追加

app/controllers/products_controller.rb
def product_params
    params.require(:product).permit(:name, :price, :image, :image_cache, :remove_image)
end

詳細画面で表示できるようにする

app/views/products/show.html.erb
<p id="notice"><%= notice %></p>

<p>
  <strong>Name:</strong>
  <%= @product.name %>
</p>

<p>
  <strong>Price:</strong>
  <%= @product.price %>
</p>

<!-- 追加箇所 開始 -->
<p>
  <strong>Image:</strong>
  <% if @product.image? %>
    <div class="thumbnail">
      <%= image_tag @product.image.url %>
    </div>
  <% end %>
</p>
<!-- 追加箇所 終了 -->

<%= link_to 'Edit', edit_product_path(@product) %> |
<%= link_to 'Back', products_path %>

参照

カスタマイズ
http://ruby-rails.hatenadiary.com/entry/20141022/1413907332

31
46
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
31
46