Devise with rails 4 authenticated root route not working

前端 未结 3 928
温柔的废话
温柔的废话 2020-12-14 08:45

What I\'m trying to do

I want to send a user to the registrations#new page if they aren\'t logged in.

After you enter login info and click submit, I want y

3条回答
  •  情歌与酒
    2020-12-14 09:36

    First, you should customize Devise::RegistrationsController (you can add file app/controllers/registrations_controller.rb)

    And see prepend_before_filter on devise registrations_controller.rb

    prepend_before_filter :require_no_authentication, :only => [ :new, :create, :cancel ]
    prepend_before_filter :authenticate_scope!, :only => [:edit, :update, :destroy]
    

    Add show action to prepend_before_filter :authenticate_scope!

    registrations_controller.rb

    class RegistrationsController < Devise::RegistrationsController
      prepend_before_filter :require_no_authentication, :only => [ :new, :create, :cancel ]
      prepend_before_filter :authenticate_scope!, :only => [:edit, :update, :destroy, :show]
    
      # GET /resource/sign_up
      def new
        super
      end
    
      # POST /resource
      def create
        super
      end
    
      # GET /resource/edit
      def edit
        super
      end
    
      def update
        super
      end
    
      # DELETE /resource
      def destroy
        super
      end
    
      def show
      end
    
    
      protected
    
      def after_sign_up_path_for(resource)
        after_sign_in_path_for(resource)
      end
    
    end
    

    Also copy the view of devise registration (edit and new template) to /app/views/registrations/ and You can make a file show.html.erb in /app/views/registrations/ folder for a profile page.

    For routes of devise looks like :

    devise_for :users, :skip => [:registrations]
    
    devise_for :users, :controllers => {
      :registrations => "registrations"
    }
    
    authenticated :user do
      devise_scope :user do
        root to: "registrations#show", :as => "profile"
      end
    end
    
    unauthenticated do
      devise_scope :user do
        root to: "registrations#new", :as => "unauthenticated"
      end
    end
    

    Last, you to set a "path" in after_sign_in_path_for(resource) and after_sign_out_path_for(resource_or_scope) at file application_controller.rb

    class ApplicationController < ActionController::Base
      protect_from_forgery
    
      private
    
       def after_sign_in_path_for(resource)
         # After you enter login info and click submit, I want you to be sent to the registrations#show page
         profile_path
       end
       def after_sign_out_path_for(resource_or_scope)
         new_user_session_path
       end
    end
    

    Note: I have tried this (to make sample apps), and it works. See log when sign in here, and log sign out here

提交回复
热议问题