Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 5.2 Rest API + Active Storage + React - Add attachment url to controller response

Would want to add the url for the attached file, while responding to get request for a nested resource (say Document) for parent resource (say Person).

# people_controller.rb  
def show
   render json: @person, include: [{document: {include: :files}}]
end


# returns
# {"id":1,"full_name":"James Bond","document":{"id":12,"files":[{"id":12,"name":"files","record_type":"Document","record_id":689,"blob_id":18,}]}


# MODELS
# person.rb  
class Person < ApplicationRecord
   has_one :document, class_name: "Document", foreign_key: :document_id
end

# document.rb
class Document < ApplicationRecord
   has_many_attached :files
end

Issue being, I want to show the file or provide a link to the file in a React frontend setup, which doesn't have helper methods like url_for. As pointed out here.

Any help, would be greatly appreciated.

like image 541
anurag Avatar asked Dec 18 '22 23:12

anurag


1 Answers

What I have done is create this method in the model

def logo_url
  if self.logo.attached?
    Rails.application.routes.url_helpers.rails_blob_path(self.logo, only_path: true)
  else
    nil
  end
end

To add logo_url to your response json you can add methods.

render json: @person, methods: :logo_url

that is explained in the official guides =)

like image 57
Juan Carlos Gama Roa Avatar answered Dec 28 '22 07:12

Juan Carlos Gama Roa