im trying to make a app
with users this users can join multiple groups - every group has the same menu on the page their group page is accessable about group/1 or group/2
so i wanted to put the the menu in the applicat开发者_运维百科ion.html.erb, with lnks depending on the group.id - but i dont know how to acces this id in the application.html.erb
This is often done using content_for
in the layout. Let's say you want your menu in a certain div in application.html.erb
:
# application.html.erb
<div id="menu_div>
<ul>
... etc ...
</ul>
</div>
Replace the inner content with a yield
statement:
<div id="menu_div>
<%= yield :group_menu %>
</div>
Then in the view template add the content_for
block:
# page
<% content_for :group_menu do %>
<ul>
... etc ...
</ul>
<% end %>
Each page template can then define its own menu code in a content_for
block. This can be further generalized by using a helper method in the block and passing in instance variables.
EDIT
Assuming @group
is assigned in the controller, you might do something like:
<% content_for :group_menu do %>
<%= show_me_the_menu(@group) %>
<% end %>
and in the helper (obviously contrived example):
def show_me_the_menu(group)
content_tag :ul do
group.users.collect do |user|
concat(content_tag(:li, user.some_method))
end
end
end
The correct approach would be to set this in ApplicationController
via before_filter
and just use it as an instance variable in views.
So in controller set something like @links =
some logic where you calculate your links based on current user.
In view you do something like:
<ul>
<%- for link in @links -%>
<li><%= link.title =>
<%- end -%.
</ul>
Of course, you set your @links in ApplicationController only if you want your links to be available to all your controllers/views, which I think you do.
Rails Cells could also be used here http://cells.rubyforge.org/
i solved my problem in a different way now. i created in the group model a "menu" and this i render partial in the application.html.erb
精彩评论