开发者

How do I make model data accessible across all controller methods efficiently?

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 开发者_JAVA技巧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?


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜