Forum: Ruby on Rails session info or variables in layouts

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
4bb313af528d968c3a35e8208ecd287b?d=identicon&s=25 Shagy Moe (shagymoe)
on 2006-12-23 18:37
Suppose I have the following:

In layouts/application.rhtml

<HTML>
<HEAD>
<TITLE> Title </TITLE>
</HEAD>

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


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

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


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...
end


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

<% if @cart %>
<table>
    <td>
      <%= link_to "My Cart", { :controller => "cart", :action =>
"my_cart" } -%>
    </td>
  </tr>
</table>
<% 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.

Thanks,

Shagy
2b891e820c238ded365d035771603f21?d=identicon&s=25 Bill Walton (Guest)
on 2006-12-24 00:56
(Received via mailing list)
Hi Shagy,

Put a before_filter at the top of your controller.

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

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

hth,
Bill
This topic is locked and can not be replied to.