如何在ActionView中訪問已在ApplicationController中定義的變量?Rails:變量訪問:從ApplicationController到ActionView
在我的情況下,我想讓我的佈局響應已在ApplicationController中設置的變量。
如果它是一個視圖,與控制器的動作相關聯,我只需要在相應的動作中設置一個實例var,並且全部都可以。但是在佈局中訪問這些數據對我來說是新事物。
謝謝!
如何在ActionView中訪問已在ApplicationController中定義的變量?Rails:變量訪問:從ApplicationController到ActionView
在我的情況下,我想讓我的佈局響應已在ApplicationController中設置的變量。
如果它是一個視圖,與控制器的動作相關聯,我只需要在相應的動作中設置一個實例var,並且全部都可以。但是在佈局中訪問這些數據對我來說是新事物。
謝謝!
您可以在ApplicationController中創建一個方法,並在您的佈局中調用該方法。這是restful_authentication(和許多其他auth插件)如何創建和管理current_user
。因此,在ApplicationController中:
def current_user
@current_user ||= User.find_by_id(session[:user_id])
end
而在你的佈局:
<% if current_user %>
<%= link_to 'logout', logout_path %>
<% else %>
<%= link_to 'login', new_user_session_path %>
<%= link_to 'register', new_user_path %>
<% end %>
這只是一個人爲的例子,但你可以看到它是如何工作的。它不是一個嚴格的變量,它是一種緩存第一次被調用的值的方法,並返回它。
我相信如果你希望在視圖中使用控制器方法,你必須使用'helper_method:current_user'。 – 2010-10-21 23:09:48
感謝你們倆!感謝Jaime提供了一個很好的例子,並感謝Jamie提供幫助者 - 我真的需要一個幫手來使它工作!現在完全好了!大! – 2010-10-22 17:38:40
我相信設置一個實例變量仍然有效。 – 2010-10-21 23:10:21