8

My environment is Rails 3.0.1 with Devise 1.1. I am developing a mobile web application, mostly with javascript, and would like to keep as much of the communication JSON-based as possible.

Is there a way for devise to respond with a success/fail message with JSON, rather than having to follow a 302 redirect and parse the HTML?

Looked at using this.

...but don't have it working.

1
  • Did you check your request accepts json? Dec 24, 2010 at 0:45

1 Answer 1

6

You can redefine the sign_in_and_redirect and sign_out_and_redirect devise helpers, to render json instead of redirecting the user.

I couldn't redefine them in an initializer, so the closest solution I found is adding this to application_controller.rb :

private

# Override the default devise signin/signout process
def sign_in_and_redirect(resource_or_scope, resource=nil)
  scope      = Devise::Mapping.find_scope!(resource_or_scope)
  resource ||= resource_or_scope
  sign_in(scope, resource) unless warden.user(scope) == resource
  # redirect_to stored_location_for(scope) || after_sign_in_path_for(resource)
  render :json => {:status => :signed_in}
end


def sign_out_and_redirect(resource_or_scope)
  scope = Devise::Mapping.find_scope!(resource_or_scope)
  if Devise.sign_out_all_scopes
    sign_out_all_scopes
  else
    sign_out(scope)
  end
  #redirect_to after_sign_out_path_for(scope)
  render :json => {:status => :signed_out}
end

If anyone has a cleaner solution, I'm also interested

1
  • 2
    overriding Devise::SessionsController seems to be much cleaner solution, like mentioned in here
    – Tombart
    Dec 6, 2011 at 15:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.