Iv4n
Iv4n

Reputation: 399

Dynamic menu with Rails (referencing outputs of two Controllers in one view)

I've been trying to find a way to display a side-menu generated from a database by the application. Since the menu needed to be user-editable, I thought the best course of action would be to create it as a scaffold and just add a 'show menu' action that would render the menu in a tree-like fashion, while the rest of the scaffold would allow admin users to modify menu items.

Now, I'm presented with a small problem - I can not figure out a way to 'call' the show menu action from application.html.erb (which I'm using as a wrapper for all actions and controllers). It has a main 'body' where it has a 'yield' line, which will obviously let whichever controller is referenced to render it's output. Before that, I would have liked to show the dynamic menu in a different part of that html.

Is that possible, and how would one go about doing that?

Because the same menu is supposed to be visible regardless of which particular action (view) is being displayed, I wanted to avoid putting the same 'menu rendering' logic in every view of every controller of my application.

Upvotes: 1

Views: 1338

Answers (1)

Moiz Raja
Moiz Raja

Reputation: 5760

From your terminology I am not entirely sure that this is what you need but here goes. If you want to reserve different sections of a layout for different type of information you can do it like so

<!-- In application.html.erb -->
<%= yield :menu %>
<!-- Main content goes here -->
<%= yield %>

Then in the view that is being rendered you can do the following if you want to show the menu.

<%= content_for :menu do %>
   <!-- Show menu -->
<% end %>

This way you can show a menu in views that you do want to show a menu in and not in others.

---UPDATE--- For a dynamic menu with menu options retrieved from db do this

In your ApplicationController add an before_filter

before_filter :fetch_menu


def fetch_menu
    @menu = #db query goes here
end

In application.html.erb

<div id="menu">
   <%@menu.each do |menu|%>
      <!-- Do something with menu -->
   <% end %>
</div>

Upvotes: 6

Related Questions