Rails:会话变量在redirect_to之后返回nil

时间:2018-06-04 06:51:22

标签: ruby-on-rails ajax api session-variables

我正在构建一个rails api

ajax请求(前端)将get请求发送到rails:

获取请求 - >登录用户控制器(用户#index) - >屏幕控制器(屏幕#index) - >发送回前端的响应。

问题:登录会话在重定向到屏幕#index时会丢失。

代码:

FRONTEND (位于:127.0.0.1/3000,允许在铁轨后端的角色)

$.ajax({
  url: "http://127.0.0.1:6536/user/index", 
  type: 'GET',
  success: function(result){
    console.log(result);
  }
});

BACKEND

路线:

 get '/user/index' => "user#index", defaults: {format: 'json'}
 get '/screen', to: 'screen#index', defaults: {format: 'json'}

UserController中:

 class UserController < ActionController::Base

   def index
     # check if user exists exists in database
     session[:user_id] = 23 

     Rails.logger.info '----------- registered user'
     Rails.logger.info session['user_id']
     redirect_to '/screen'
   end
 end

ScreenController:

 class ScreenController < ActionController::Base

   def index
     Rails.logger.info '----------- fetching user'
     Rails.logger.info session['user_id']

     user = User.find(session['user_id']) # do something with the user
     render json: { status: 'registered' }, status: :ok
   end
 end

输出

 Started GET "/user/index" for 127.0.0.1 at 2018-06-04 11:50:24 +0530
 Processing by UserController#index as JSON
 ----------- registered user
 23
 Redirected to http://127.0.0.1:6536/screen
 Completed 302 Found in 34ms (ActiveRecord: 10.5ms)


 Started GET "/screen" for 127.0.0.1 at 2018-06-04 11:50:24 +0530
 Processing by ScreensController#index as JSON
 ----------- fetching user

 User Load (0.5ms)  SELECT  "users".* FROM "users" WHERE "users"."id" IS NULL LIMIT   [["LIMIT", 1]]
 Completed 500 Internal Server Error in 5ms (ActiveRecord: 0.5ms)

ScreenController具有nil会话值。为什么会话在控制器重定向之间丢失?

如果我在浏览器中显示页面http://127.0.0.1:6536/user/index,它运行正常。

Rails登录浏览器搜索:

 Started GET "/user/index" for 127.0.0.1 at 2018-06-04 12:26:51 +0530
 Processing by UserController#create as JSON
 ----------- registered user
 23
 Redirected to http://127.0.0.1:6536/screen
 Completed 302 Found in 1ms (ActiveRecord: 0.0ms)


 Started GET "/screen" for 127.0.0.1 at 2018-06-04 12:26:51 +0530
 Processing by ScreenController#index as JSON
 ----------- fetching user
 23
 Completed 200 OK in 2ms (Views: 0.4ms | ActiveRecord: 0.0ms)

1 个答案:

答案 0 :(得分:0)

您需要添加重定向代码并在AJAX调用的成功部分执行条件渲染

function make_ajax_call(url){
      $.ajax({
      url: url, 
      type: 'GET',
      success: function(response) {
         if (response.redirect){
           make_ajax_call(response.redirect); // will make a recursive call
         }
          else
         {
          console.info(response.body);
        }
       }
    });
}