Search code examples
ruby-on-railsrails-apiactioncontroller

How can i call render from inside a Service class or model Class?


My service authenticate some data on the user's role basis. If the query params are wrong, i want to exit the code and render some error message as the api response?

render json: 'something' and return

Error that i get it:

 "status": 500,
"error": "Internal Server Error",
"exception": "#<NoMethodError: undefined method `render' for AuthenticationService:Class>",
"traces": {
    "Application Trace": [

Solution

  • The short answer is: you can't.

    For something like authentication or permission checking it would be more common to ask your service to authenticate and then that service would either return a value that you can react to or throw an exception that you can react to.

    That way each part of your code can take responsibility for what it needs to and no more. Your service can authenticate and your controller can call render.

    So, for example, you might end up with something like this in your service:

    def authenticate!
      if !okay
        raise AuthenticationError
      end
    end
    

    And in your controller:

    def my_action
      begin
        AuthenticationService.new.authenticate!
      rescue AuthenticationError
        render json: 'something' and return
      end
    end
    

    (This is a very basic example - and I've made up an error class and an okay method to demonstrate)