Help us understand the problem. What is going on with this article?

carrierwave と fog を使ってasset hostを決める

やりたいこと

取得する画像のURLをホスティングしているサーバーのURL付きで欲しい。

現状、localhost:3000(バックエンド)とlocalhost:4000(フロントエンド)で分けて開発しているが、

画像のURLを取得すると、以下のようになっている。

{ url: "uploads/user/profile_image/1/adcb24fe3b95a9f70fa81f2cf5c6e8ec.jpg" }

ので、以下のように変更したい。

{ url: "http://localhost:3000/uploads/user/profile_image/1/adcb24fe3b95a9f70fa81f2cf5c6e8ec.jpg" }

tl:dr

config/initializers/carrierwave.rbを作成し、asset_hostを設定する。

Gemのインストール

carrierwaveuploader/carrierwave

※本番環境では、GCPを使うので、あらかじめこのようんな設定にしています。

Using Google Storage for Developers

Fog is used to support Google Storage for Developers. Ensure you have it in your Gemfile:

gem "fog-google"
gem "google-api-client", "> 0.8.5", "< 0.9"
gem "mime-types"

設定

Railsプロジェクトにconfig/initializers/carrierwave.rbを作成する。

~/config/initializers/carrierwave.rb
CarrierWave.configure do |config|
  config.fog_provider = "fog/google"
  if Rails.env.production?
    config.fog_credentials = {
      provider: "Google",
      google_storage_access_key_id: ENV["GCS_ACCESS_KEY_ID"],
      google_storage_secret_access_key: ENV["GCS_ACCESS_KEY"],
      path_style: true,
    }

    config.fog_directory = ENV["GCS_BUCKET"]
  end
  config.asset_host = ENV["ASSET_HOST_IMG"]
  config.fog_attributes = { "Cache-Control" => "max-age=3600" }
end

ローカルのenv設定

ASSET_HOST_IMG=http://localhost:3000
Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away