85
100

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

railsで画像アップロードの方法

Last updated at Posted at 2019-05-12

##使用準備##
###gemインストール###
/Gemfile

gem 'carrierwave'
gem 'rmagick'
  • carrierwaveはアップロードするために必要
  • rmagickは画像をリサイズする
$ bundle install

エラーが出る場合インストールする

yum -y install libjpeg-devel libpng-devel
yum -y install ImageMagick ImageMagick-devel

###アップローダ作成###

$ rails g uploader image

###カラム追加###

$ rails g migration AddImageToUsers image:string
$ rails db:migrate
  • アップロードしたファイル格納用

###Model修正###
app/models/users.rb

  mount_uploader :image, ImageUploader

###Controller修正###
app/controllers/users_controller.rb

params.require(:user).permit(:image)
  • ストロングパラメータに追加

###Uploader設定変更###
app/uploader/image_uploader.rb

#リサイズ、画像形式を変更に必要
  include CarrierWave::RMagick

#上限変更
  process :resize_to_limit => [700, 700]

#JPGで保存
  process :convert => 'jpg'

#サムネイルを生成
  version :thumb do
    process :resize_to_limit => [300, 300]
  end

# jpg,jpeg,gif,pngのみ
  def extension_white_list
    %w(jpg jpeg gif png)
  end

#ファイル名を変更し拡張子を同じにする
  def filename
    super.chomp(File.extname(super)) + '.jpg' 
  end

#日付で保存
  def filename
    if original_filename.present?
      time = Time.now
      name = time.strftime('%Y%m%d%H%M%S') + '.jpg'
      name.downcase
    end

##View変更##
###入力フォーム###

<%= f.label :image 'iamge' %>
<%= f.file_field :image %>

###表示方法###

<% if @user.image? %>
  <%= image_tag @user.image.url %>
<% else %>
  <%= image_tag "noimage.gif %>
<% end %>
  • サムネイルを表示する時は、.image.thumb.urlとする
  • .imageはカラム名
85
100
2

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
85
100

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?