0

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 !

3 Answers 3

1

There are multiple ways of achieving what you want. You could merge! the response into the jbuilder root.

json.merge! @response

The above merges all key/value-pairs into the jbuilder root. You could also opt to extract! specific attributes.

json.extract! @response, :error

Alternatively you can simply render it in the controller, since you've already composed the structure the following would be enough.

render json: @response
Sign up to request clarification or add additional context in comments.

1 Comment

most complete response even if the others were right. Thanks, no view = better !
0

You can do this for jBuilder:

json.merge!(@response)

Source

Comments

0
class MyController < ApplicationController
  def getTracklist

    begin
     # you need to assign something to a variable
    rescue StandardError => e
      respond_to do |format|
        format.any(:json, :js) do
          render :json => {:error => e.message}
        end
      end
    end
  end
end

Making these changes to your controller can help you with your requirements. You don't need a view after doing this.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.