【问题标题】:Rails landing page routing and deviseRails 登陆页面路由和设计
【发布时间】:2025-12-25 11:45:07
【问题描述】:

我的网站应该像 facebook.com 一样工作。 如果用户已登录并且转到“/”,则它应该呈现为 home 控制器。如果它没有被记录,它应该是渲染 landing_page 控制器

"/" && user_signed_in? ---> home 控制器

"/" && user_not_logged ---> landing_page 控制器

我正在使用 Rails 4 和 Devise

应用控制器

class ApplicationController < ActionController::Base

  before_filter :authenticate_user!
end

Routes.rb

get "landing_page/index"

root 'home#index', :as => :home

如何在除“landing_page”控制器之外的每个控制器中运行的 ApplicationControl 中保留一个“before_filter”?

更新

如果我转到“/en/landing_page”,它会正确呈现landing_page 控制器(注销),但如果我转到“/”,它会将我重定向到“/users/sign_in”

class LandingPageController < ApplicationController
  skip_before_action :authenticate_user!

  def index
  end

end

class ApplicationController < ActionController::Base

  before_action :authenticate_user!

end

Routes.rb

 root 'landing_page#index'

【问题讨论】:

    标签: ruby-on-rails devise ruby-on-rails-4 rails-routing


    【解决方案1】:

    解决了!

    登陆页面控制器

    class LandingPageController < ApplicationController
      skip_before_action :authenticate_user!
    
      def index
      end
    
    end
    

    HomeController

    class HomeController < ApplicationController
      skip_before_action :authenticate_user!
      before_action :check_auth
    
    def check_auth
        unless user_signed_in?
            redirect_to :controller => :landing_page
        end
    end
     end 
    

    应用控制器

    class ApplicationController < ActionController::Base
    
      before_action :authenticate_user!
    
    end
    

    Routes.rb

     root 'landing_page#index'
    

    【讨论】:

    • 这不是说无论你是否登录,如果你尝试访问'/',它总是会呈现登陆页面?难道你不想将根设置为 HomeController#index (或其他将 check_auth 的东西)
    【解决方案2】:

    我认为你可以在控制器中编写confirm_logged_in 函数动作

    before_filter :confirm_logged_in

    在该函数中,您可以提及您希望如何根据登录用户呈现页面

    def confirm_logged_in<br>
      unless session[:user_id]
      flash[:notice] = 'Please log in.'
      redirect_to(:controller => 'access', :action => 'login')
      return false #halts the before_filter<
    
    else
    return true
      end
    end
    

    【讨论】:

      【解决方案3】:

      我认为您可以轻松添加一个前置过滤器来处理此操作。

      喜欢这个answer

      【讨论】:

      • 不。如果我转到“/”,它仍然会将我重定向到 /users/sign_in。问题已更新