I'm new to Ruby, trying to building an API.
I've followed a tutorial and was able to return a JSON response when calling an API endpoint.
In this example, the function called raises an error that I want to pass as a JSON response.
my_controller.rb
class MyController < ApplicationController
def getTracklist
begin
importer = #this raises an error
rescue StandardError => e
@response = {
error: e.message,
}
return @response
end
end
end
my view look like this :
getTracklist.json.jbuilder
json.response @response
thing is,
this works but renders my response as
{"response":{"error":"the error message"}}
while I want it as
{"error":"the error message"}
I made an attempts by changing my view to
json @response
but it fails :
ActionView::Template::Error (undefined method `json' for <#:0x0000559304675470> Did you mean? JSON): 1: json @response
So how could I render my response "fully" without having to put it in a property ?
I've also seen when reading stuff about ROR that this code is sometimes used, and I was wondering how I could use it in this situation :
render json: { error_code:'not_found', error: e.message }, status: :not_found
Thanks !