簡體   English   中英

Ruby on rails全局變量?

[英]Ruby on rails global variable?

我正在嘗試將當前用戶設置為變量,以在每個頁面上顯示“以Joe身份登錄”。 不確定從哪里開始......

任何快速提示? 具體來說,這樣的文件應該是什么...

我當前的用戶可以定義為(我認為): User.find_by_id(session[:user_id])

TY :)

您可能希望使用Authlogic或Devise之類的東西來處理這個問題,而不是滾動自己的auth系統,尤其是當您不熟悉Rails應用程序中常見的設計模式時。

也就是說,如果你想在問題中做你想要的,你應該在你的ApplicationController中定義一個方法,如下所示:

def current_user
  @current_user ||= User.limit(1).where('id = ?', session[:user_id])
end

您從所有常規控制器上的ApplicationController繼承,因此它們都可以訪問current_user方法。 此外,您可能希望在視圖中將該方法作為幫助程序進行訪問。 Rails也會照顧你(也在你的ApplicationController中):

helper_method :current_user
def current_user ...

注意:如果使用find_by_x方法,如果沒有返回任何內容,它們將引發ActiveRecord :: RecordNotFound錯誤。 您可能不希望這樣,但您可能想要一些東西來阻止非用戶訪問僅用戶資源,Rails再次為您提供:

class ApplicationController < ActionController::Base
  protect_from_forgery
  helper_method :current_user
  before_filter :require_user

private
  def current_user
    @current_user ||= User.limit(1).where('id = ?', session[:user_id])
  end

  def require_user
    unless current_user
      flash[:notice] = "You must be logged in to access this page"
      redirect_to new_session_url
      return false
    end
  end
end

干杯!

它屬於您的控制器。

正是出於這個原因,所有控制器都來自Application Controller。 在Application Controller中創建一個返回所需內容的方法,然后您可以在任何其他控制器中訪問它。

暫無
暫無

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

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