Navigating with Rails and Devise: How to send the user back to the original page after logging in successfully?

I have implemented the idiom described in this resource

# /app/controllers/application_controller.rb

class ApplicationController < ActionController::Base
  before_filter do |controller|
    redirect_to new_login_url unless controller.send(:logged_in?)
  end

After a successful sign-in, how can I:

  1. Determine if the signing in process was successful,
  2. Redirect the user to the requested controller action?
  3. Implement the login-process via AJAX and JSON?

Additionally, I am encountering the following Error Message:

uninitialized constant ApplicationController::LoginFilter 

When trying out a more complex solution from 6.2 Other Ways to Use Filters which involves modifying my Controller structure as follows:

# /app/controllers/application_controller.rb

class ApplicationController < ActionController::Base
  before_action :set_return_path, LoginFilter

  def set_return_path
    return if devise_controller?
    session['user_return_to'] = request.url unless current_user
  end

  class LoginFilter

    def self.filter(controller)
      unless controller.send(:logged_in?)
      controller.flash[:error] = "You must be logged in"
      controller.redirect_to controller.new_login_url
    end

   end
  end   
end

Thank you,

von Spotz

Answer №1

If you want to store the requested page URL, you can implement a before_action in the application_controller.rb:

class ApplicationController < ActionController::Base
  before_action :store_requested_page_url

  def store_requested_page_url
    return if devise_controller?

    session['user_return_to'] = request.url unless current_user
  end
end

Next, you can redirect the user to this stored URL after they successfully sign in:

class SessionsController < Devise::SessionsController
 
  def after_sign_in_path_for(resource)
    return root_url if session['user_return_to'].blank?

    session['user_return_to']
  end

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error 500 in WordPress Child Theme due to AJAX Internal Issue

I have encountered an issue with my Ajax code in the Js/Jq block (/buscador/menuLateral/menu-libros.php): $.ajax({ url: '<?= get_stylesheet_directory_uri(); ?>' + '/buscador/buscador-functions.php', type: 'POST' ...

Switching a Rails/Ajax form from create to update mode upon submission

While experimenting with a star ratings page, I encountered an issue where the form element remained in "Create" mode instead of updating to an "Update" method after submission. The rating form is ajaxified, but it lacks the functionality to dynamically sw ...

Tips for retrieving a td element from an HTML document

I have a variable containing HTML data and I need to extract a specific td element from it. When I use the alert(returnData) function, it displays the following output: <tr class='addedrow'> <td id="abc">DOM-001 <inpu ...

Invoking code behind functions through ajax requests to dynamically display items one by one

I'm currently working with calling code behind functions from an ajax call. I have recently developed a method called Post, which returns a list of values. My goal is to verify these values from the client side by displaying them in an alert message. ...

send multiple textbox values to controller in CodeIgniter

I am new to Codeigniter and I'm facing some difficulties in understanding how to accomplish a task. In my view page, there are five rows generated using a for loop. Each row consists of two select boxes and two input boxes. I don't know how to re ...

Looking for a .NET MVC AJAX search solution. How can I enhance the code below?

I am looking to implement a search functionality using AJAX. I have tried using the get method in my controller by passing the search string, but it is not working as expected. Below is a snippet of my controller code, where I retrieve the search value fr ...

Attempting to send an AJAX request using jQuery, receiving a successful response but encountering an error with the AJAX functionality

My AJAX request in jQuery is as follows: $.ajax({ url: "http://someurl.stuff.com", beforeSend: function(xhr) { xhr.setRequestHeader("Accept", "application/json"); xhr.setRequestHeader("Host",null); xhr.setRequestHeader("Access ...

Is there a method to verify the consumability of an API without having to make a direct request to it?

I'm working on an idle timer feature where the API will be called to update data once the timer runs out. How can I check if the API is still usable without actually sending a request? ...

Tips for concurrently and asynchronously executing multiple AJAX requests

I am working with a javascript object named Agendamento which includes the following key parts: const Agendamento = { // ... storeResultados: async function (consulta) { //... $.ajax({ type: 'POST', ...

Require assistance in understanding JSON data in the form of a variable

Apologies for any language barriers, but I have encountered a problem that I need help with. I am trying to create a highchart from an AJAX call. The following code works perfectly: chartOptions = { chart: { renderTo: 'grafica1', type: 'ar ...

What is the best way to show a div after successfully sending a post value using AJAX?

How do I show this specific div after a successful AJAX post? This is what I want to display: <div class="love" id="love_0" style="border-radius: 3px; padding: 8px; border: 1px solid #ccc; right: 13px; background: #fff; top: 13px;"> <a class ...

JavaScript: Utilize MooTools to extract a string containing a specific class and then pass it through a parent function

I am facing a major issue and struggling to find a solution for it. My problem involves returning values, mostly strings, that I can utilize in various contexts. For instance, I need to verify whether something is 0 or 1 in an if/else statement, or insert ...

"Is there a way to ensure that jPlayer plays the same song even after a page refresh

I have been working on integrating jPlayer with Ajax to ensure that when the page of my website is refreshed, jPlayer will continue playing its current song seamlessly. I have successfully stored track information and the current track during refresh, ho ...

Halt period indicated in the document specifying the designated timeframe

If I have two files named index.php and fetch.php The contents of index.php are as follows: <script> $(document).ready(function(){ setInterval(function(){ $('#fetch').load('fetch.php') }, 1000); }); </sc ...

Dealing with excessively large data for json_encode in PHP

In my Symfony project, I am facing an issue while trying to retrieve database data through AJAX. Specifically, when attempting to json_encode all estimates from our database (over 60k in total), I encounter an out of memory error. Interestingly, if I try t ...

Protect your Laravel and Vue SPA from CSRF attacks by securely storing the JWT token in an HttpOnly cookie

Frontend uses Vue.js for the single page application (SPA). The backend is built on Laravel framework. The frontend and backend are decoupled, communicating with each other through xhr requests. Initially, I stored the JWT token in local storage for aut ...

This route does not allow the use of the POST method. Only the GET and HEAD methods are supported. This limitation is specific to Laravel

I am encountering an issue while attempting to submit an image via Ajax, receiving the following error message: The POST method is not supported for this route. Supported methods: GET, HEAD. Here is the Javascript code: $("form[name='submitProfi ...

Struggling to retrieve Json data through Ajax in Rails 5

Hey there! I'm currently exploring the world of Rails action controllers with Ajax, and I've run into a bit of a snag. I can't seem to retrieve Json data and display it in my console.log using my Ajax function. The GET method works perfectly ...

Guide to building a Wordpress sidebar with AJAX

Utilizing responsive design on my website has been great overall, but I have encountered an issue with the site appearing too long on mobile devices. The sidebar, filled with widgets such as popular posts and recent comments, takes up too much vertical spa ...

What steps can I take to avoid page displacement when implementing jQuery ajax tabs?

There are numerous inquiries regarding this issue, and it appears that some are very similar to what I am looking for, such as: JQuery UI Tabs Causing Screen to "Jump" Stop jquery TABS from jumping / scrolling up when clicked on? Jquery tabs: How do I ...