LoginSignup
0
0

More than 5 years have passed since last update.

RailsのControllerで画像のprefix付きパスを取得する

Posted at

Rails の Controller から render json で画像ファイルパスをJSONで返すアクションを作ろうとしました。
画像ファイルパスは下記の構成のテーブルの filename カラムに格納されています。

migration.rb
create_table :images do |t|
  t.string :filename
  t.timestamps
end

そして下記の Controller を作り、画像パスを image_path で取得し render しようとしました。

controller.rb
@images = Image.all
@images = @images.map do |image|
  image.filename = image_path(image.filename)
  image
end
render json: @images

しかし View と Controller とでは image_path の挙動が違うらしく、 Controller では画像ファイル名に prefix が付かないみたいです。

これについては下記のサイトで「完全にバグとしか言えない」と言われております。
Rails image_pathの動作が違う

上記サイトには解決方が載っておりますが、自分は上手く行きませんでした...。

ですが、下記のように image_path の代わりに ActionView::Base.new.image_path を使うことで、画像ファイル名に prefix が付いたパスを取得することが出来ました。


@images = Image.all
@images = @images.map do |image|
  view_context = ActionView::Base.new
  image.filename = view_context.image_path(image.filename)
  image
end
render json: @images

因みに view で正常に動作するなら jbuilder を使えば良いのでは?ということについては自分も考えて試しましたが、何故か Controller と同じ動作をしてしまい上手く行かなかったです。

0
0
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
0
0