2

How do I access in an ActionView a variable, that has been defined in the ApplicationController?

In my case, I'd like to make my layout respond to a variable that's been set-up in the ApplicationController.

If it were a view, associated with a controller's action, I'd only need to set-up an instance var in the corresponding action and all would be OK. But accessing such data in the layout is something new to me.

Thanks!

Albus Dumbledore
  • 12,368
  • 23
  • 64
  • 105

1 Answers1

2

You can create a method in ApplicationController, and call that method in your layouts. This is how restful_authentication (and many other auth plugins) create and manage current_user. So in ApplicationController:

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

And in your layout:

<% if current_user %>
  <%= link_to 'logout', logout_path %>
<% else %>
  <%= link_to 'login', new_user_session_path %>
  <%= link_to 'register', new_user_path %>
<% end %>

This is just a contrived example, but you can see how it works. It's not strictly a variable, it's a method that caches the value of the first time it is called, and returns that.

Jaime Bellmyer
  • 23,051
  • 7
  • 53
  • 50
  • 1
    I believe if you wish to use controller methods in a view, you have to `helper_method :current_user`. – Jamie Wong Oct 21 '10 at 23:09
  • Thanks to both of you! Thanks to Jaime for the nice example, and thanks to Jamie for suggesting helpers – I really needed a helper to make it work! It's all perfectly fine now! Great! – Albus Dumbledore Oct 22 '10 at 17:38