LoginSignup
107
96

More than 5 years have passed since last update.

rails ユーザー画像アップロードの手順

Last updated at Posted at 2016-02-18

gemのインストール

gemfile

gem 'carrierwave'
gem 'rmagick'

rmagickはサイズ調整に必要。
アップロードされる画像を特定のサイズに調整して保存してくれる。

2016.7/28追記:
rmagick入れる時にエラーが出る方へ。
自分もvagrantのCentOS7でやろうとしたら以下のエラーでた。

Building native extensions.  This could take a while...
ERROR:  Error installing rmagick:
    ERROR: Failed to build gem native extension.

    /home/vagrant/.rbenv/versions/2.1.2/bin/ruby extconf.rb
checking for gcc... yes
checking for Magick-config... no
checking for pkg-config... yes
Package MagickCore was not found in the pkg-config search path.
Perhaps you should add the directory containing `MagickCore.pc'
to the PKG_CONFIG_PATH environment variable
No package 'MagickCore' found
checking for outdated ImageMagick version (<= 6.4.9)... *** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of necessary
libraries and/or headers.  Check the mkmf.log file for more details.  You may
need configuration options.

Provided configuration options:
    --with-opt-dir
    --without-opt-dir
    --with-opt-include
    --without-opt-include=${opt-dir}/include
    --with-opt-lib
    --without-opt-lib=${opt-dir}/lib
    --with-make-prog
    --without-make-prog
    --srcdir=.
    --curdir
    --ruby=/home/vagrant/.rbenv/versions/2.1.2/bin/ruby

extconf failed, exit code 1

Gem files will remain installed in /home/vagrant/.rbenv/versions/2.1.2/lib/ruby/gems/2.1.0/gems/rmagick-2.15.4 for inspection.
Results logged to /home/vagrant/.rbenv/versions/2.1.2/lib/ruby/gems/2.1.0/extensions/x86_64-linux/2.1.0-static/rmagick-2.15.4/gem_make.out

この時は、
$ sudo yum -y install ImageMagick
$ sudo yum -y install ImageMagick-devel
$ gem install rmagick
このコマンドを打ってからbundle install すれば行けると思います。

アップローダーの作成

$ rails g uploader image
app/uploaders/image_uploader.rb の作成

usersのカラムにimageを追加

$ rails g migration add_image_to_users image:string

Userモデルにこれを追加

user.rb
 mount_uploader :image, ImageUploader

UserControllerのstrong parameterに:imageを追加

users_controller.rb

private
  def user_params
    params.require(:user).permit(:name, :email,,:password, :password_confirmation, :image, :remember_digest)
  end

アップローダーの設定の変更

image_uploader.rb
class ImageUploader < CarrierWave::Uploader::Base  

 # リサイズしたり画像形式を変更するのに必要
  include CarrierWave::RMagick

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

  # 保存形式をJPGにする
  process :convert => 'jpg'

  # サムネイルを生成する設定
   version :thumb do
     process :resize_to_fill => [40, 40, gravity = ::Magick::CenterGravity]
   end

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

 # 拡張子が同じでないとGIFをJPGとかにコンバートできないので、ファイル名を変更
  def filename
    super.chomp(File.extname(super)) + '.jpg' if original_filename.present?
  end



end

_form.html.erbでフォームを作成する

_form.html.erb

    <%= form_for(@user) do |f| %>
      <%=f.label :image,"ユーザー画像" %>
      <%= f.file_field :image %>
    <% end %>
  </div>
</div>

表示させる

edit.html.erb

<%= form_for @user,:url => {:action => 'update'}, :html => {:multipart => true} do |f| %>

  <%= f.file_field :image %><br>
  <%= f.submit %>

<% end %>

users_controller.rb

class UsersController < ApplicationController
  def show
    @user = User.find(params[:id])
    @tweets = @user.tweets.all
  end

  def edit
    @user = User.find(params[:id])
  end

 def update
   @user = User.find(params[:id])
   if @user.update(user_params)
     redirect_to user_show_path(@user)
  else
    render :edit
  end
 end

  private

  def user_params
    params.require(:user).permit(:name, :email, :profile, :image)
  end
end
107
96
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
107
96