Forum: Ruby on Rails session info or variables in layouts

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
Shagy M. (Guest)
on 2006-12-23 19:37
Suppose I have the following:

In layouts/application.rhtml

<TITLE> Title </TITLE>

  <%= render(:partial => "shared/navigation_bar") -%>
  <%= @content_for_layout -%>

and in the partial (shared/_navigation_bar) I have:

      <%= link_to "My Cart", { :controller => "cart", :action =>
"my_cart" } -%>

My question is...How can I toggle whether the "My Cart" link is shown
depending on if there is anything in the cart?

If I put:

def some_action
  @cart = find_cart
  ...some other code...

I can reference this is the partial(which is in the layout) like this:

<% if @cart %>
      <%= link_to "My Cart", { :controller => "cart", :action =>
"my_cart" } -%>
<% end %>

However, if I don't include the code in EVERY action, there will be an
error for that page.  The DRY principle tells me I should not just be
adding the @cart = find_cart code to every dang action on the controller
just so I can have a little logic in the nav bar.  So, what is the best
way to do this?  The find_cart method is a private method in the
application controller.


Bill W. (Guest)
on 2006-12-24 01:56
(Received via mailing list)
Hi Shagy,

Put a before_filter at the top of your controller.

before_filter :find_cart, :except => [:index,

It'll run the find_cart action for every action in the controller except
ones you tell it not to.

This topic is locked and can not be replied to.