Ruby 2.5.3 Rails 5.2.4.2 gem: fog-aws
I introduced CarrierWave for image posting with Rails, but I encountered many errors while using gem: fog-aws, so I thought that it would be difficult for those who will introduce it from now on, so I decided to leave the settings. It was.
If it is the same environment, the following configuration file should be OK for carrierwave.rb.
config/initializers/carrierwave.rb
require 'carrierwave/storage/abstract'
require 'carrierwave/storage/file'
require 'carrierwave/storage/fog'
CarrierWave.configure do |config|
if Rails.env.development? || Rails.env.test?
config.storage = :file
config.enable_processing = false if Rails.env.test?
elsif Rails.env.production?
config.fog_provider = 'fog/aws'
config.fog_credentials = {
provider: 'AWS',
aws_access_key_id: ENV["AWS_ACCESS_KEY_ID"],
aws_secret_access_key: ENV["AWS_SECRET_ACCESS_KEY"],
region: 'ap-northeast-1'
}
config.storage = :fog
config.fog_directory = 'Your S3 bucket name'
config.asset_host = 'https://s3.ap-northeast-1.amazonaws.com/Your S3 bucket name'
end
end
CarrierWave::SanitizedFile.sanitize_regexp = /[^[:word:]\.\-\+]/
-Images are retained in AWS S3 only in the production environment. The development environment is saved locally. -Be careful about the storage directory of carrierwave.rb. app / config / initializers / carrierwave.rb.
carrierwave.rb
CarrierWave::SanitizedFile.sanitize_regexp = /[^[:word:]\.\-\+]/
This code at the bottom is a sentence that enables carrierwave to be used because Japanese cannot be used in the file name by default. You can prevent garbled characters.
carrierwave.rb
aws_access_key_id: ENV["AWS_ACCESS_KEY_ID"],
aws_secret_access_key: ENV["AWS_SECRET_ACCESS_KEY"]
For, specify environment variables in your .env file.
I had a lot of trouble setting up S3, so I'd like to keep it in the screenshot.
The properties of my bucket in S3. Only logging is enabled. By the way, all the detailed settings below are also invalid.
Block public access. Only two are turned on.
Bucket policy editor. Please change the bucket name etc. by yourself.
I'll put the code below so that I can copy it.
Bucket policy
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "Stmt000001",
"Effect": "Allow",
"Principal": {
"AWS": "Your user's ARN(Confirmed from IAM)"
},
"Action": "s3*",
"Resource": "arn:aws:s3:::Your S3 bucket name"
}
]
}
No other items have been set.
CarrierWave is convenient for image resizing, but it was a little difficult to deploy to AWS EC2 and use S3. I would also like to study Active Storage. I hope it will be an article to help someone even a little!
Recommended Posts