ruby-on-railsrender

Rails render return does not stop execution


In my app I have this situation:

In some_controller.rb, I have a code about this:

def start
  method1(param)
  ....
  if some_case
    render json: {ok: "ok"}
  end
end

def method1
  ...
  if some_case
    render json: {error: "Some error"}
    return
  end
end

When it's time to render a json with error, I get a double render error. It advises me to use render .. and return. I've tried even that, and still get this error. Is this because render does not break execution itself, but just returns something to a caller method? If it's so, what can I do in my case? The thing is method1 is a big method and I surely want it to be separated from the start method. And in case there are no reasons to render an error there, I want the execution of start to be continued.


Solution

  • Consider using filter instead. This works:

    before_action :method1, only: :start
    def start
      ....
      if some_case
        render json: {ok: "ok"}
      end
    end
    
    def method1
      ...
      if some_case
        render json: {error: "Some error"}
        return
      end
    end
    

    When render occurs in filter, it does not run action itself then, so no double render occurs.