开发者

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

开发者 https://www.devze.com 2022-12-20 14:35 出处:网络
I have a cart which contains items, in my controller index method I use @cart = find_cart to find my cart\'s items.

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

精彩评论

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

关注公众号