Cleaner way to get nested data in API? #4906
-
I have a model, I'm trying to use the Solidus API to access these documents. I can do that in an initializer: Spree::Api::Config.configure do |config|
config.product_attributes.push(:variant_docs)
end But it doesn't give me everything I want. I really want is the attachment's path, but that isn't included by default. I have to write a json.variant_docs(product.variant_docs) do |doc|
json.name(doc.name)
json.path(doc.path_to_file)
end But I'm wary of overwriting the whole view just to get this data. Is there a cleaner way to do it? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
@michaelmichael I didn't try but, according to jbuilder documentation, you could create a class Document
# ...
def to_builder
Jbuilder.new do |doc|
json.name(doc.name)
json.path(doc.path_to_file)
end
end
end so that jbuilder knows how to render that attribute. Let me know if that works! |
Beta Was this translation helpful? Give feedback.
-
I've more or less solved this by prepending a module Spree::Product::AddDocBuilder
def doc_builder
return nil unless variant_docs.any?
docs = []
variant_docs.map do |doc|
docs.push({
name: doc.name,
attachment: doc.path_to_file,
position: doc.position,
id: doc.id
})
return docs
end
end
end Then I just include that in the API config initializer: Spree::Api::Config.configure do |config|
config.product_attributes.push(…, :doc_builder)
end Seems like jbuilder just formats it correctly! |
Beta Was this translation helpful? Give feedback.
I've more or less solved this by prepending a
doc_builder
method onSpree::Product
that maps over documents and returns an object containing the data I want.Then I just include that in the API config initializer:
Seems like jbuilder just formats it correctly!