2
1

More than 1 year has passed since last update.

ビューやコントローラー以外で `user.avatar` のurlにアクセスする

Posted at

ビューやコントローラーでは url_forrails_blob_path といったヘルパーメソッドが使える。しかし、それ以外の箇所ではこれらのメソッドをそのまま使うことができないため、ファイルのURLにアクセスするには Rails.application.routes.url_helpers.rails_blob_path のような長い記述が必要になる。

開発環境の場合は特に default_url_options[:host]localhost:3000 などにセットしておく必要がある。

development.rb
Rails.application.routes.default_url_options[:host] = 'localhost:3000'

また include Rails.application.routes.url_helpers のようにすることで rails_blob_path をそのまま使えるようにすることも可能。

class User < ApplicationRecord
  has_one_attached :avatar
end

class UserSerializer < ActiveModel::Serializer
  include Rails.application.routes.url_helpers

  def avatar
    rails_blob_url(object.avatar) if object.avatar.attached?
  end
end

参考

2
1
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
2
1