3
6

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.

rails6でcarrierwave実装(aws-s3)

Posted at

rails6でcarrierwaveを実装使用としたら
動機: gem 'fog'で実装しようとしたらエラー出たので
出ないようにした。

プロジェクトを作成

[ターミナル]

mkdir [プロジェクト名]
cd [プロジェクト名]
rails new . -d postgresql
rails db:create

Slimの導入

echo 'gem "slim-rails"' >> Gemfile
echo 'gem "html2slim"' >> Gemfile
bundle
bundle exec erb2slim app/views/layouts/ --delete

rails6 & carrierwave

photoモデルをつくって、imageカラムに画像をアップロード出来るように設定します。

インストール

echo "gem 'carrierwave'" >> Gemfile
echo "gem 'fog-aws'" >> Gemfile
echo "gem 'rmagick'" >> Gemfile
bundle

実装例

rails g scaffold photo image
rails db:migrate
rails generate uploader Image

carrierwaveの設定

/app/uploaders/image_uploader.rb
class ImageUploader < CarrierWave::Uploader::Base

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

  # 画像の上限を640x480にする
    process :resize_to_limit => [640, 480]



  if Rails.env.development?
      storage :fog
  elsif Rails.env.test?
      storage :file
  else
      storage :fog
  end

  def store_dir
      "uploads/#{model.class.to_s.underscore}"
  end

  def extension_whitelist
      %w(png jpg)
  end
  # filenameをuuid
  def filename
      "#{secure_token}.#{file.extension}" if original_filename.present?
  end

  protected
    def secure_token
        var = :"@#{mounted_as}_secure_token"
	model.instance_variable_get(var) or model.instance_variable_set(var, SecureRandom.uuid)
    end
end

AWS S3の認証情報をcredentialsに追加

rails credentials:edit
aws:
  access_key_id: いつもの
  secret_access_key: いつもの

s3_fog_directory: S3のバケット名

前半で設定した内容を元に設定する

  • aws_access_key_id S3用に用意したIAMユーザーのアクセスキー
  • aws_secret_access_key S3用に用意したIAMユーザーのシークレットアクセスキー
  • region S3のリージョン
  • config.fog_directory S3のバケット名
config/initializers/carrierwave.rb
CarrierWave.configure do |config|
  config.fog_credentials = {
    provider: 'AWS',
    aws_access_key_id: Rails.application.credentials.dig(:aws, :access_key_id),
    aws_secret_access_key: Rails.application.credentials.dig(:aws, :secret_access_key),
    region: 'ap-northeast-1'
  }

  config.fog_directory  = Rails.application.credentials.dig(:s3_fog_directory)
  config.cache_storage = :fog
end
app/models/photo.rb
class Photo < ActiveRecord::Base
  mount_uploader :image, ImageUploader
end
app/views/photos/_form.html.slim
= f.file_field :image
app/views/photos/show.html.slim
= image_tag photo.image.to_s

参考文献

3
6
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
3
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?