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.
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 =)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With