Ajax调用后Rails控制器方法不重新加载页面

时间:2014-07-03 21:23:02

标签: jquery ruby-on-rails ajax authentication render

因此,我构建了一个身份验证方法,该方法充当控制器中其他方法的前置过滤器。基本上,如果用户没有登录,我希望该方法重定向到根路径。这是我的authenticate_user!在过滤方法之前:

def authenticate_user!
      unless current_user
        flash[:notice] = "Your session has ended. Please login again."
        render js: "window.location.pathname = '#{root_path}'"
      end
end

我遇到的问题是窗口本身没有重新加载,而是页面中的内容元素和显示的文本:" window.location.pathname =' /& #39;&#34 ;.我无法使用redirect_to(我找到了similar question here),因为它似乎只是将某个内容元素发送回root_path(而导航栏之类的元素保持不变)。这就是为什么我一直在寻找一个完整的窗口重新加载。任何帮助将不胜感激。

使用服务器日志进行编辑

Started GET "/projects/editHeader?fileName=test.csv" for 127.0.0.1 at 2014-07-04 10:37:21 -0400
Processing by ProjectsController#editHeader as TEXT
  Parameters: {"fileName"=>"test.csv"}
Filter chain halted as :authenticate_user! rendered or redirected
Completed 200 OK in 2ms (Views: 0.1ms | ActiveRecord: 0.0ms)


Started GET "/projects/headerDataPreview?fileId=NaN" for 127.0.0.1 at 2014-07-04 10:37:21 -0400
Processing by ProjectsController#headerDataPreview as TEXT
  Parameters: {"fileId"=>"NaN"}
Filter chain halted as :authenticate_user! rendered or redirected
Completed 200 OK in 1ms (Views: 0.1ms | ActiveRecord: 0.0ms)

2 个答案:

答案 0 :(得分:2)

使用ajax请求,您需要在before_filter方法中指定请求类型

将您的authenticate_user!方法更改为

def authenticate_user
  unless current_user
    if request.xhr? # if its a ajax request then redirect with javascript
      flash.keep[:notice] = 'Bla bla bla' # keeps the flash message for next request
      render :js => "window.location = '#{root_path}'"
    else
      flash[:notice] = "Bla bla bla"
      redirect_to root_path
    end
  end
end

答案 1 :(得分:0)

首先 - 将js放入控制器是不好的做法。不要将客户端脚本与服务器处理的控制器混合关于你的问题 - 你为什么不使用rails redirect?

def authenticate_user!
  unless current_user
    redirect_to root_path, :notice => "Your session has ended. Please login again."
  end
end