Two things I would like to point out. First, you probably do not want to make this request every time you produce any page in your application. You definitely want to cache your MenuItems. Secondly, it would be useful to put a convenience method in the MenuItems class to cache this value. So, if I define a method
def MenuItem.all_for_menu @@all_for_menu ||= MenuItem.find(:all)
I can call MenuItem.all_for_menu in my layout and get all menu items. When you add a new one or edit it, you will have to invalidate it.
Another caching method would be to put the data in a partial and cache fragment using a standard caching call:
<% cache(:controller => "menu_items", :action => "list", :action_suffix => "all_menu_items") do %> <%= render :partial => "menu", :collection => MenuItem.all_for_menu %> <% end %>
You can then complete this snippet by calling:
expire_fragment(:controller => "menu_items", :action => "list", :action_suffix => "all_menu_items")
MattMcKnight
source share