Where is the recommended place to store variable instances for layouts

If you have a layout that has a menu that gets its menu items from the database. Where is the recommended place in a Rails application to host this call and assign it to the instance variable that the layout uses?

1. @menuitems # exists in application.html.erb
2. @menuitems = MenuItem.find(:all) # code exists somewhere (where should this exist?)

@womble - Yes, it would be useful to use before_filter, but I would have to include it in all controllers using this layout, or is this what I can add to application_controller.rb if child controllers and companion views can see this variable copy?

+3
source share
3 answers

, before_filter . . , .

memoization , set - , current_user. memoization. :

def menu_items
  @menu_items ||= MenuItem.all
end
helper_method :menu_items

menu_items , @menu_items.


, , . /, , LayoutHelper. helper :all ( helper :layout) .

- , ActiveRecord. , , , .

+8

MVC Rails. - ( ).

  • , , - /
0

This type of call must exist at the system controller level. Since it looks like it should happen all over the world, I would probably put it in before_filterand hate myself for it. Getting the data needed for the layout is a bit inconvenient in Rails, no matter how you do it.

0
source

Source: https://habr.com/ru/post/1703240/


All Articles