2
2

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 5 years have passed since last update.

(3STEP)画像のアップロード機能をつける

Posted at

paperclipを使って画像のアップロード機能をつける

①paperclipのインストール

ImageMagickをインストールする。

terminal
$ brew install imagemagick

ImageMagickとは、コマンドラインより画像を操作したり表示するためのツールです。インストールされたかの確認は、terminalよりコマンド$ brew listと打ち込めばできます。

paperclipのgemをインストールします。

gemfile
gem "paperclip"

bundle installします。インストール後はサーバーを再起動すると反映されます。

terminal
$ bundle install

インストールされたgemは、「Gemfile.lock」ファイルに格納されています。

Gemfile.lock
GEM
  remote: https://rubygems.org/ 
        paperclip (4.3.0)
  

②usersテーブルにpaperclip用のカラムを追加する

コマンド$rails g paperclipでマイグレーションファイルを追加します。

terminal
$ #rails g paperclip モデル名 カラム名
$  rails g paperclip user image_url
$ #マイグレーションファイル実行
$  bundle exec rake db:migrate

③userモデルにpaperclipの設定を追記

Userモデルにアイコン画像の設定をすることで、画像のアップロードができるようになります。

■has_attached_file
画像のサイズやデフォルトの画像、保存先を指定できます。
default_urlには、画像が設定されていない場合に表示するデフォルト画像の格納先を指定します。

user.rb
class User < ActiveRecord::Base
$  has_attached_file :image_url,
        styles:  { medium: "画像サイズ", thumb: "画像サイズ" } 
   default_url: "画像格納先"

■validates_attachment_content_type
画像のサイズや種類でバリデーションを設定します。

user.rb
class User < ActiveRecord::Base
 validates_attachment_content_type :image_url,                             
                                    content_type: ["画像の種類"]

種類と指定方法

指定方法 備考
image/jpg jpgファイル
image/png pngファイル
image/gif gifファイル
2
2
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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?