crazydiv
crazydiv

Reputation: 842

Render and return from helper function

I have multiple actions in different controllers making 3rd party API calls through Faraday using a helper function defined in application_helper.

Now in case of a successful response, they have different views to render, but need to send json which was recieved if there was any error. The following code works when used directly in an action,

if (r[:error] && r[:code]==403)
    Rails.logger.info "Exiting"
    render :json => body and return
end

But if I move it to a helper function and call the helper function from the action, the execution doesn't stop there and continues till the end of the action where it raises DoubleRendererError.

Could anything be done to make the controller stop processing and return itself from the helper (to avoid placing these 4 lines in every action, where I make the 3rd party API call)

Upvotes: 2

Views: 1649

Answers (2)

Matthew-Israelson
Matthew-Israelson

Reputation: 11

def blank_fields?(params)
if params["user"]["email"].blank? || params["user"]["password"].blank? || params["user"]["password_confirmation"].blank?
  render json: { status: 422, message: "Your email, password or password confimation is blank. Please check that all fields are filled in and try again!" }, status: 422
  return true # pass back to guard clause
end
end

do something like this, and call this method from your controller method, aka:

return if blank_fields?(params)

Upvotes: 1

chad_
chad_

Reputation: 3819

Rails' helpers are intended for calling from views, and they way you're using render is to be called from a controller. You can call helpers from within a controller but it's generally not necessary. If you want some function to be available to all controllers, you would typically place it in your ApplicationController.

When you call render within a view, it is going to try to render a partial at the point in the template you called it.

Upvotes: 0

Related Questions