How to use format.js when credentials are incorrect and redirect when credentials are correct?

StackOverflow https://stackoverflow.com/questions/13294342

  •  27-11-2021
  •  | 
  •  

Pergunta

I am using Authlogic gem for user sessions.

The login form is shown in a modal, so if the user credentials are incorrect, I want to display the error message on the modal, thats why I use remote: true.

<%= form_for @user_session, url: user_session_path, ***remote: true do |f| %>

I want to respond_to format.js when the user_session had errors, and redirect_back_or_default root_path when user_session is saved correctly

The problem I am having, is that if the credentials are correct, the page is not redirected.

Here is a screenshot of the resulting requests for a request with proper credentials: Requests

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

new.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)
Foi útil?

Solução

Try the following hack instead of redirect:

render :js => "window.location = '/index/'"

replace /index with whatever your root url is. It seems Rails is looking for javascript type response for both cases since you used ajax

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top