学生向けプログラミング入門 | 無料

学生向けにプログラミングを無料で解説。Java、C++、Ruby、PHP、データベース、Ruby on Rails, Python, Django

【学習5.0】【MacOSX】アマゾンS3

アプリケーションをデプロイする場合レンタルサーバでは写真の保存ができません。
そのためアップロードした写真の保存先にアマゾンS3を利用する必要があります。


アマゾンS3のキーの取得方法は以下の手順でお願いします。
mrradiology.hatenablog.jp


記述追加 config\environments\development.rb(72行目)
バケット名、アクセスキー、シークレットキーはご自分のものを入れて下さい。

config.paperclip_defaults = {
  storage: :s3,
  path: ':class/:attachment/:id/:style/:filename',
  s3_host_name: 's3-ap-northeast-1.amazonaws.com',
  s3_credentials: {
    bucket: 'winrailslearn',
    access_key_id: 'AKIAIU4EZ4WK4HU35G4Q',
    secret_access_key: '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',
    s3_region: 'ap-northeast-1'
  }
}



config\environments\development.rb

Rails.application.configure do

  Paperclip.options[:command_path] = "C:\Program Files\ImageMagick-7.0.10-Q16;C:\Program Files (x86)\GetGnuWin32\bin"

  # Settings specified here will take precedence over those in config/application.rb.

  # In the development environment your application's code is reloaded on
  # every request. This slows down response time but is perfect for development
  # since you don't have to restart the web server when you make code changes.
  config.cache_classes = false

  # Do not eager load code on boot.
  config.eager_load = false

  # Show full error reports.
  config.consider_all_requests_local = true

  # Enable/disable caching. By default caching is disabled.
  if Rails.root.join('tmp/caching-dev.txt').exist?
    config.action_controller.perform_caching = true

    config.cache_store = :memory_store
    config.public_file_server.headers = {
      'Cache-Control' => 'public, max-age=172800'
    }
  else
    config.action_controller.perform_caching = false

    config.cache_store = :null_store
  end

  # Don't care if the mailer can't send.
  config.action_mailer.raise_delivery_errors = true

  config.action_mailer.perform_caching = false

  # Print deprecation notices to the Rails logger.
  config.active_support.deprecation = :log

  # Raise an error on page load if there are pending migrations.
  config.active_record.migration_error = :page_load

  # Debug mode disables concatenation and preprocessing of assets.
  # This option may cause significant delays in view rendering with a large
  # number of complex assets.
  config.assets.debug = true

  # Suppress logger output for asset requests.
  config.assets.quiet = true

  # Raises error for missing translations
  # config.action_view.raise_on_missing_translations = true

  # Use an evented file watcher to asynchronously detect changes in source code,
  # routes, locales, etc. This feature depends on the listen gem.
  # config.file_watcher = ActiveSupport::EventedFileUpdateChecker

  config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }
  
  #Gメールの設定
  config.action_mailer.delivery_method = :smtp
  config.action_mailer.smtp_settings = {
    address: "smtp.gmail.com",
    port: 587,
    enable_starttls_auto: true,
    authentication: "plain",
    user_name: 'win.rails.learn@gmail.com',
    password: 'vusopllqzbyvvahk'
  }

  # アマゾンS3
  config.paperclip_defaults = {
    storage: :s3,
    path: ':class/:attachment/:id/:style/:filename',
    s3_host_name: 's3-ap-northeast-1.amazonaws.com',
    s3_credentials: {
      bucket: 'winrailslearn',
      access_key_id: 'AKIAIU4EZ4WK4HU35G4Q',
      secret_access_key: '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',
      s3_region: 'ap-northeast-1'
    }
  }

end



記述追加 GemFile(85行目)

gem 'aws-sdk', '~> 2.8'



GemFile

source 'https://rubygems.org'

git_source(:github) do |repo_name|
  repo_name = "#{repo_name}/#{repo_name}" unless repo_name.include?("/")
  "https://github.com/#{repo_name}.git"
end


# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '~> 5.0.7', '>= 5.0.7.1'
# Use postgresql as the database for Active Record
gem 'pg', '>= 0.18', '< 2.0'
# Use Puma as the app server
gem 'puma', '~> 3.0'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .coffee assets and views
gem 'coffee-rails', '~> 4.2'
# See https://github.com/rails/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby

# Use jquery as the JavaScript library
gem 'jquery-rails'
# Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks
gem 'turbolinks', '~> 5'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.5'
# Use Redis adapter to run Action Cable in production
# gem 'redis', '~> 3.0'
# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'

# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development

group :development, :test do
  # Call 'byebug' anywhere in the code to stop execution and get a debugger console
  gem 'byebug', platform: :mri
end

group :development do
  # Access an IRB console on exception pages or by using <%= console %> anywhere in the code.
  gem 'web-console', '>= 3.3.0'
  gem 'listen', '~> 3.0.5'
  # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
  gem 'spring'
  gem 'spring-watcher-listen', '~> 2.0.0'
end

# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]

# bulma
gem 'bulma-rails', '~> 0.7.4'
gem 'bulma-extensions-rails', '~> 1.0.30'

# デバイス
gem 'devise', '~>4.2'

# アバター
gem 'gravtastic'

# toastr
gem 'toastr-rails', '~> 1.0'

# 日本語化
gem 'rails-i18n'

# google認証
gem 'omniauth'
gem 'omniauth-google-oauth2'

# 管理ダッシュボード
gem 'activeadmin'

# 管理ダッシュボードのテーマ
gem 'active_skin'

#画像アップロード
gem 'paperclip', '~> 5.1.0'

# アマゾンS3
gem 'aws-sdk', '~> 2.8'



コマンド
bundle
バージョンをV3に上げてくださいとメッセージが出ますが、気にしなくて大丈夫です。


コマンド サーバ起動
rails s


ブラウザ確認
http://localhost:3000/admin/projects/1


テストでローカルにアップロードした画像は表示されなくなりました。

テスト画像確認
テスト画像確認



画像をアップロードしなおしてみます。

もう一度アップロード
もう一度アップロード



無事画像が更新されました。

画像更新
画像更新

アマゾンS3の自分のバケットを見てみましょう。

アップロード成功
アップロード成功


アップロード成功
アップロード成功



これで画像がアマゾンS3に保存されるようになりました。

関連記事(外部サイト)