LoginSignup
1
6

More than 3 years have passed since last update.

Carrierwaveの導入で手間取ったので忘備録。

Last updated at Posted at 2019-07-14

1.まずは公式ページを。

2.Imagemagickのインストール

$ brew install imagemagick

3.Gemのインストール

$ gem install carrierwave

4.Gemfileの編集

gem 'carrierwave'
gem 'mini_magick'

からの、、bundel install

5.postsテーブルに image column を追加

$ rails g migration add_image_to_posts image:string

6.uploader ファイルを作成

$ rails g uploader image

7.models/post.rb を編集

以下を追加

mount_uploader :image, ImageUploader

8.posts_controller のストロングパラムズを編集

:image,:image_cache を追加

def post_params
   params.require(:post).permit(:title,:content,:image,:image_cache)
end

9.image_uploader の編集

include CarrierWave::MiniMagick

  storage :file

  def store_dir
    "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
  end

# 画像の上限を700pxにする
  process :resize_to_limit => [700, 700]

# jpg,jpeg,gif,pngしか受け付けない
  def extension_white_list
    %w(jpg jpeg gif png)
  end

10.new page

注意:image_tagの前にfが付くとエラーになるので気をつけて!!

<div>
    <%= f.label :image %>
    <%= image_tag @post.image.url if @post.image? %>
    <%= f.file_field :image %>
    <%= f.hidden_field :image_cache %>
</div>

11.confirm page

<h1>Are you ok?</h1>
<%=form_with(model:@post,url:posts_path,local:true)do |f|%>
  <%=f.hidden_field :title%>
  <%=f.hidden_field :content%>
  <%=f.hidden_field :image_cache%>

  <p>Title:<%=@post.title%></p>
  <p>Content:<%=@post.content%></p>
  <p>Image:<%=@post.image.url %></p>
  <%=f.submit 'OK!'%>
<% end %>

<%=form_with(model:@post,url:new_post_path,local:true,method:'get')do |f|%>
  <%=f.hidden_field :title%>
  <%=f.hidden_field :content%>
  <%=f.hidden_field :image_cache%>
  <%=f.submit 'Back!',name:'back'%>
<% end %>

12.index page

<div>
        <% if post.image? %>
        <%= image_tag post.image.url %>
        <% else %>
        <p>No Image</p>
        <% end %>
 </div>

13.show page

<div>
    <% if @post.image? %>
    <%= image_tag @post.image.url %>
    <% else %>
    <p>No Image</p>
    <% end %>
</div>

以上です。

注意点)

当初、以下のようなサムネイル作成メソッドをimage_uploaderに入れていたが、それが原因で日本語名の画像ファイルが文字化けしてエラーとなっていた。
これを削除すると日本語名の画像ファイルも正常にアップロードできるようになった。

version :thumb do
    process :resize_to_limit => [300, 300]
  end
1
6
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
6