LoginSignup
10
10

More than 5 years have passed since last update.

paperclipとS3で画像をアップロード

Last updated at Posted at 2017-01-05

AWSクラウドストレージサービスのS3を用いて、paperclipでアップロードした画像をheroku上で表示されるようにする。
Paperclipは画像だけでなく各種ファイルをアップロードする機能をRailsアプリケーションに組み込むことのできるgemです。

前提条件
・AWSのアクセスキーとシークレットキーを持っている
・AWSでBUCKETを作成済み

今回はProjectテーブルのimageカラムに適用させていきます。
まずimageカラムを作成

command
$ bundle exec rails g migration AddAttachmentImageToProject
7834653827_add_attachment_image_to_projects.rb
class AddAttachmentImageToProjects < ActiveRecord::Migration
  def self.up
    change_table :projects do |t|
      t.attachment :image
    end
  end

  def self.down
    remove_attachment :projects, :image
  end
end

command
$ rake db:migrate
=> image_file_name,
    image_content_type ,
    image_file_size,
    image_updated_at
の4つのカラムをpaperclipで作ってくれる
Gemfile
gem 'paperclip', '~> 5.0'
gem 'aws-sdk', '~> 2.3' # AWS

$ bundle install

s3の設定

config/environments/production.rb


Rails.application.configure do

  `
  `

  # s3の設定

  config.paperclip_defaults = {
  :storage        => :s3,
  :bucket         => ENV['S3_BUCKET_NAME'],
  :s3_region      => ENV['AWS_REGION'],
  :s3_host_name   => 's3-ap-northeast-1.amazonaws.com',
  :s3_credentials => {
    access_key_id: ENV['AWS_ACCESS_KEY_ID'],
    secret_access_key: ENV['AWS_SECRET_ACCESS_KEY']
  }
}

end

モデルに画像情報を追記

Projectテーブルのimageカラムに指定しています

app/models/project.rb

class Project < ActiveRecord::Base

  has_attached_file :image, 
                    :path => ":attachment/:id/:style.:extension",
                    styles: { medium: "680x300>", thumb: "170x75>" }, 
                    default_url: "/images/:style/missing.png" 

  validates_attachment_content_type :image, content_type: /\Aimage\/.*\Z/ # 
end
config/initializers/paperclip.rb
Paperclip::Attachment.default_options[:url] = 's3user-magict2017.s3.amazonaws.com' # '[バケット名].s3.amazonaws.com'という形にすると良いっぽいです。

herokuに環境定数を設定する

$ heroku config:set S3_BUCKET_NAME=your_bucket_name 
$ heroku config:set AWS_ACCESS_KEY_ID=your_access_key_id
$ heroku config:set AWS_SECRET_ACCESS_KEY=your_secret_access_key
$ heroku config:set AWS_REGION=your_aws_region
command
$ heroku config     # 環境変数の設定を一覧で確認できる

ここまでできたら設定は終了です。
好きなようにviewから呼び出して見てください

commmand
$ git add .
$ git com -m 's3'
$ git push origin master
$ git push heroku master
$ heroku run rake db:migrate

herokuでエラー出たら
$ heroku logs -t でログを確認ください

参考URL
https://devcenter.heroku.com/articles/paperclip-s3
http://blog.kakeragames.com/2016/02/03/heroku-paperclip-s3.html
http://ruby-rails.hatenadiary.com/entry/20140716/1405443484

10
10
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
10
10