簡體   English   中英

路由根以顯示登錄用戶的用戶帖子和未登錄的靜態頁面

[英]Routing root to display user's posts for logged in users and static page for non-logged in

故事:未登錄的用戶應該看到一個歡迎靜態頁面,當他登錄時,他應該看到他的博客帖子列表。

我想正確的方法是將root路由到列出所有用戶帖子然后檢查身份驗證的操作。 如果用戶未登錄,則呈現歡迎頁面?

我需要幫助為posts控制器編寫一個動作,該控制器顯示登錄用戶的帖子。

我有這個問題,但不想重定向(添加延遲和更改網址)所以我決定在Rails 3中用戶為中心的路由中建議的約束或使用Lambdas for Rails 3路由約束中提到的范圍路由

約束

root :to => "landing#home", :constraints => SignedInConstraint.new(false)

范圍路線

scope :constraints => lambda{|req| !req.session[:user_id].blank? } do
  # all signed in routes
end

routes.rb中:

root :to => "posts#index"

post_controller.rb

class PostsController < ApplicationController
  before_filter :authenticate_user!

  def index
    @posts = current_user.posts.all
  end
end

如果用戶未登錄,則過濾器捕獲此信息並重定向到某處(登錄?錯誤消息?)。 否則,將調用index方法並呈現索引視圖。 這可以開箱即用,如果你滾動另一個身份驗證,你需要調整和/或編寫自己的幫助,例如:

application.html.erb

class ApplicationController < ActionController::Base
  protect_from_forgery

  helper_method :current_user
  helper_method :user_signed_in?

  private  
    def current_user  
      @current_user ||= User.find_by_id(session[:user_id]) if session[:user_id]  
    end

    def user_signed_in?
      return 1 if current_user 
    end

    def authenticate_user!
      if !current_user
        flash[:error] = 'You need to sign in before accessing this page!'
        redirect_to signin_services_path
      end
    end 
end

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM