Reputation: 17
I'm trying to retrieve the URL of an active storage attachment as JSON response but i didn't quite get the correct respond here is my code:
#projet.rb
class Projet < ApplicationRecord
has_many :appartements, dependent: :destroy
has_one_attached :image_de_couverture
has_one_attached :situation
has_many_attached :images
end
#projet_serializer.rb
class ProjetSerializer < ActiveModel::Serializer
include Rails.application.routes.url_helpers
attributes :id, :nom, :gouvernorat, :localite, :surface, :description, :en_cours, :fini,
:situation, :images, :image_de_couverture
def images
object.images.map do |image|
rails_blob_path(image, only_path: true) if object.images.attached?
end
end
def image_de_couverture
polymorphic_url(object.image_de_couverture, only_path: true) if
object.image_de_couverture.attached?
end
def situation
polymorphic_url(object.situation, only_path: true) if object.situation.attached?
end
end
#projets_controller.rb
class ProjetsController < ApplicationController
# show all projects
def index
@projets = Projet.all
render json: @projets
end
def set_projet
@projet = Projet.find(params[:id])
end
def projet_params
params.require(:projet).permit(:nom, :gouvernorat, :localite, :surface, :description, :situation, images: [])
end
end
and here is the response i get with this code
[
{
id: 1,
nom: "Test",
gouvernorat: "Test",
localite: "Test",
surface: 30303,
description: "Test",
en_cours: true,
fini: true,
situation: "/rails/active_storage/blobs/redirect/eyJfcmFpbHMiOnsibWVzc2FnZSI6IkJBaHBFdz09IiwiZXhwIjpudWxsLCJwdXIiOiJibG9iX2lkIn19--50589feef3ab662f5fb9877dbf4f0a21c79e2412/lame_rideau1.jpg",
images: [
"/rails/active_storage/blobs/redirect/eyJfcmFpbHMiOnsibWVzc2FnZSI6IkJBaHBEdz09IiwiZXhwIjpudWxsLCJwdXIiOiJibG9iX2lkIn19--0550f31bd4e562c76dfd1aff9f0beac6483e1651/1.jpg",
"/rails/active_storage/blobs/redirect/eyJfcmFpbHMiOnsibWVzc2FnZSI6IkJBaHBFQT09IiwiZXhwIjpudWxsLCJwdXIiOiJibG9iX2lkIn19--11ec06652e38fc43b54ef93187905f4591115d3c/2.jpg",
],
image_de_couverture: null
},
]
instead of
"/rails/active_storage/blobs/redirect/eyJfcmFpbHMiOnsibWVzc2FnZSI6IkJBaHBEdz09IiwiZXhwIjpudWxsLCJwdXIiOiJibG9iX2lkIn19--0550f31bd4e562c76dfd1aff9f0beac6483e1651/1.jpg"
i want to the link to the attachment.
Thanks in advance.
Upvotes: 0
Views: 1465
Reputation: 454
Try changing the rails_blob_path
helper by rails_blob_url
in your ProjetSerializer#images
. You also need to set the host config in your application file. source
# config/application.rb
class Application < Rails::Application
...
routes.default_url_options = { host: 'localhost:3000' }
end
Upvotes: 1
Reputation: 625
def images
object.images.map do |image|
Rails.application.routes.url_helpers.rails_blob_url(image, only_path: true) if object.images.attached?
end
end
Upvotes: 0