views:

11

answers:

1

I have a cart which contains items, in my controller index method I use @cart = find_cart to find my cart's items.

I'm trying to make a simple cart link which contains the amount of items in the cart at the top of my application layout using: <%= @cart.items.length %> It will look like cart(2), if you have two items.

Without being repetitive (that is adding @cart = find_cart to every single controller method) how do I efficiently make this data available across my entire application?

+3  A: 

You will want to use a before_filter and place it in your Application Controller:

class ApplicationController < ActionController::Base
    before_filter :find_cart_items


    private
    def find_cart_items
       @cart = find_cart
    end
end

Then, in any of your controllers where you do not want to find the cart, just use:

skip_before_filter :find_cart_items
Doug Neiner
obvious! I should have thought of it.
JZ