我正在使用 Authlogic gem 进行用户会话。
登录表单以模式显示,因此如果用户凭据不正确,我想在模式上显示错误消息,这就是我使用remote: true
.
<%= form_for @user_session, url: user_session_path, ***remote: true do |f| %>
当user_session有错误时我想respond_to format.js,当user_session正确保存时我想redirect_back_or_default root_path
我遇到的问题是,如果凭据正确,则不会重定向页面。
以下是具有正确凭据的请求的结果请求的屏幕截图:
user_sessions_controller.rb
class UserSessionsController < ApplicationController
before_filter :require_no_user, :only => [:new, :create]
before_filter :require_user, :only => :destroy
def new
@user_session = UserSession.new
if @user_session.save
redirect_back_or_default root_path
else
format.js
end
end
def create
@user_session = UserSession.new(params[:user_session])
if @user_session.save
flash[:notice] = "Login successful!"
redirect_back_or_default root_path
else
render :action => :new
end
end
def destroy
current_user_session.destroy
flash[:notice] = "Logout successful!"
redirect_to authentications_path
end
end
新的.js.erb
(function($){
<% if @user_session.errors.any? %>
$errorsContainer = $("#login-errors").empty();
<% @user_session.errors.full_messages.each do |msg| %>
$errorsContainer.append('<div class="alert alert-error"><%= msg %></div>');
<% end %>
<% end %>
})(jQuery)