Rails 3 + devise - 如何使用JSON进行回应 [英] Rails 3 + devise - How to get devise to respond with JSON

查看:122
本文介绍了Rails 3 + devise - 如何使用JSON进行回应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的环境是Rails 3.0.1与Devise 1.1。我正在开发移动Web应用程序,大多数都是使用javascript,并且希望尽可能多地保持基于JSON的通信。



有没有办法设计使用JSON响应成功/失败的消息,而不必遵循302重定向并解析HTML?



使用这个



...但没有工作。 >

解决方案

您可以重新定义sign_in_and_redirect和sign_out_and_redirect设计助手,以渲染json而不是重定向用户。



我无法在初始化程序中重新定义它们,所以我发现最接近的解决方案是将其添加到application_controller.rb中:

  private 

#覆盖默认设计登录/注销进程
def sign_in_and_redirect(resource_or_scope,resource = nil)
scope = Devise :: Mapping.find_scope!(res我们可以通过这个方法来实现这个功能,但是我们可以通过这个方法来实现这个功能:(1)
resource || = resource_or_scope
sign_in(scope,resource) 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)
如果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

如果有人有一个更清洁的解决方案,我也很感兴趣


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.

解决方案

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

这篇关于Rails 3 + devise - 如何使用JSON进行回应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆