简体   繁体   中英

load bootstrap modal on redirect

I have a bootstrap modal that allows users to sign in. I want users that have not authenticated to have that sign modal pop on whatever page they are at.

Session Controller

  def new
    respond_to do |format|
      format.html
      format.js
    end
  end

session/new.js.erb

$("#modal-window").html("<%= escape_javascript(render 'sessions/new') %>");

If a user hit this controller I would want them to see the signin modal. I figured I would try to redirect them the new_session_path . That didn't work and I got a missing template error.

  def new
    if current_user
      @image = Image.new
    else
      redirect_to new_session_path
    end
  end

If you send an html request, you should get html back. Rails is looking for an html template and isn't finding one.

I would recommend using a before_action for any controllers or actions you want to restrict. This would require making an html template for sign in.

before_action :verify_user, only: [:new]

def verify_user
  redirect_to new_session_path and return unless current_user
end

(Or you could redirect_to the root_path or somewhere and trigger the modal on page load.)

As for the modal, I would listen for clicks on the links you want to restrict.

# users.js.coffee
$ ->
  $('body.not-signed-in a.require-sign-in').click, ->
    $.get $('body').data('sign-in-path')
    return false

Which means you'd have to add those classes in the html.

<body class="<%= current_user ? 'signed-in' : 'not-signed-in' %>" data-sign-in-path="<%= new_session_path %>">
  <%= link_to 'link', some_path, class: 'require-sign-in' %>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM