首页 > 解决方案 > 在rails中使用ajax重定向/渲染模式

问题描述

我有一个 Rails 应用程序,我需要在其中检查用户在使用特定页面时是否未通过身份验证,然后它应该在同一页面上显示登录模式,并且背景应该被淡化。

为此,我authenticate user在应用程序控制器中调用了一种方法

def authenticated_user
 if user
 else
  # from here I want to open a sign in modal
 end
end

我目前的sessions/new方法如下,

class SessionsController < ApplicationController
  def new
   respond_to do |format|
      format.html
      format.js
    end
  end
end

我在视图的会话文件夹中也有 new.js.erb,

$("#modal-window").find(".modal-content").html("<%= escape_javascript( render 'sessions/new', formats: [ :html ]) %>");
$("#modal-window").modal();

我已经尝试通过以下方式发送 ajax 请求,

redirect_to sessions_path(format: :js)

但它反而会重定向我,http://localhost:3000/reader/login.js而不是在同一页面上打开模式。

标签: javascriptruby-on-railsrubyajax

解决方案


根据我以前的经验,这无法通过redirect_to sessions_path(format: :js)

您可以尝试以下方法:

对于 before_action

def authenticated_user
  if user
  else
    if request.xhr?
      render :authenticated_user and return
    else
      redirect_to request.env['HTTP_REFERER'], flash: { authenticated_user: true }
    end
  end
end

在布局文件中:

...
- if flash[:authenticated_user]
  <%= render 'authenticated_user_modal' %>
...

认证用户.js.erb

<% html = capture do %>
  <%= render 'authenticated_user_modal' %>
<% end %>

$('body').append('<%=j html %>');
$('#modal-window').modal();
# add a method that remove the modal after close it.
# $(document).on('close-modal', '#modal-window', function () {
#   $('#modal-window').remove();
# });

_authenticated_user_modal.html.erb

<div id="modal-window">
  ...
</div>

:javascript
  $('#modal-window').modal();

推荐阅读