我有以下相当简单的代码,应该使用Devise将用户登录到我的应用程序中。如果使用HTML请求而不是XHR完成,这实际上可以正常工作。当我这样做的时候,XHR就是这样做的,
= form_for(@user, :url => session_path(@user), :remote => true) do |f|
= f.label :email
= f.text_field :email, :size => 15, :maxlength => 32
= f.label :password
= f.password_field :password, :size => 15, :maxlength => 32
%br
= f.submit "Sign in"
结果是:
Started GET "/" for 127.0.0.1 at 2012-12-04 13:24:44 -0800
Processing by HomeController#index as HTML
Rendered home/_hello_page.html.haml (0.1ms)
Rendered home/index.html.haml within layouts/application (1.9ms)
Completed 200 OK in 18ms (Views: 16.3ms | ActiveRecord: 0.4ms)
Started POST "/users/sign_in" for 127.0.0.1 at 2012-12-04 13:24:54 -0800
Processing by Devise::SessionsController#create as JS
Parameters: {"utf8"=>"✓", "authenticity_token"=>"1cGaycA20NMhK0fOwQyN8e3aSFwCHB6BZcLwmvKTI3U=", "user"=>{"email"=>"obscured@someplace.com", "password"=>"[FILTERED]"}, "commit"=>"Sign in"}
Completed 500 Internal Server Error in 65ms
ActionView::MissingTemplate (Missing template devise/sessions/create, devise/create, application/create with {:locale=>[:en], :formats=>[:js, :html], :handlers=>[:erb, :builder, :coffee, :haml]}. Searched in:
* "/Users/sxross/Developer/iPhoneApps/motion/whos_here/whos_here_server/app/views"
* "/Users/sxross/.rvm/gems/ruby-1.9.3-p327@whos_here_server/gems/devise-2.1.2/app/views"
):
一切都和我期望的一样,很明显Processing by Devise::SessionsController#create as JS
正在告诉接收控制器“把我送回我想要的JSON”。所以问题是为什么Devise控制器试图渲染模板而不是JSON,我该怎么做才能修复它?
谢谢!
答案 0 :(得分:1)
您在views / devise / sessions中缺少create.js. [erb | haml]文件
当您发送远程登录请求时,请求由Devise :: SessionsController#create完成,如果您不覆盖它
respond_with resource, :location => after_sign_in_path_for(resource)
将查找create.js.erb。 我原告只是
window.location = "<%= root_url %>"
在其中。
另外,您需要设置
config.http_authenticatable_on_xhr = false
config.navigational_formats = [:"*/*", "*/*", :html, :js]
在config / initializers / devise.rb中为此工作。
我为自己的情况用这个覆盖了会话控制器:
@resource = warden.authenticate!(:scope => resource_name, :recall => "sessions#failure")
sign_in(resource_name, @resource)
respond_to do |format|
format.html { respond_with @resource, :location => after_sign_in_path_for(@resource) }
format.js
end
如果身份验证失败,会抛出一个失败方法,并在failure.js.erb中处理它以向用户显示