9
8

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.

Rails ActiveStorage で PUBLIC な URL を表示する

Last updated at Posted at 2019-04-18

Rails 5.2 を触り始めて、 ActiveStorage で時間制限がある URL しか取得できなかったので、 PUBLIC な URL 取得するためのメモ

Post モデルに、 has_one_attached :image してる想定

$ bin/rail c
irb(main):001:0> post = Post.first
irb(main):002:0> post.image.attachment.service.send(:object_for, post.image.key).public_url
=> "https://your-bucket-name.s3.ap-northeast-1.amazonaws.com/dfadadfDEfadfadfaf"

これで URL が取得できます
ただ、これだけだとプライベートなファイルのままで、ブラウザで開いても、表示されないので、 ココが一番のポイント
S3 側のバケットポリシーを変更します

{
    "Version": "2008-10-17",
    "Statement": [
        {
            "Sid": "AllowPublicRead",
            "Effect": "Allow",
            "Principal": "*",
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::your-bucket-name/*"
        }
    ]
}

そうすると、上の URL で表示されるようになります!

9
8
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
9
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?