我是Ruby on Rails noob。我在Ruby on Rails上通过Michael Hartl的tutorial工作。到目前为止,我在第3章关于静态页面。到目前为止,我的StaticPage
控制器有三个视图:home
,help
和about
。控制器的布局如下:
<!DOCTYPE html>
<html>
<head>
<title><%= yield(:title) %> | Sample App</title>
<%= csrf_meta_tags %>
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
<%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
</head>
<body>
<%= yield %>
</body>
</html>
我现在要做的是添加菜单栏,即所有静态页面的链接列表。到目前为止,我在<body>
标记处有类似内容:
<ul>
<% '???'.each do |page| %>
<li>Page!</li>
<% end %>
</ul>
我无法弄清楚要放什么而不是'???'
- 我需要一个控制器所有视图的迭代器。提前谢谢。
答案 0 :(得分:0)
您要求的不仅仅是添加静态页面。您需要一个支持数据库model
来存储动态创建的页面,并使用controller
来处理model
操作,这样您就可以生成collections
。
使用collections
,您就可以拥有类似
<ul>
<% '???'.each do |page| %>
<li><%= page %></li>
<% end %>
</ul>
由于您正在使用该教程,因此您需要渲染您的菜单栏
<ul>
<li><%= link_to "Home", home_path %></li>
<li><%= link_to "Help", help_path %></li>
<li><%= link_to "About", about_path %></li>
</ul>
答案 1 :(得分:0)
You can render something from the database in the controller and use it in the views. Like in the controller, I can write @ones = Something.all
in a method called one
and if I have a show method in the controller who shows one record from the database depending on the argument it takes, then I can add a link as below and it will take me to something_show_path/:something_id
.
<% @ones.each do |one|%>
<%= link_to "#{one}", something_show_path(@one) %>
<% end %>
But in this case, there is no record of the static pages you have in the database. So, if you want a syntax like that in the views, add them in an array in the controller like
def whatever
```rest of the code````
@pages = ["home", "about", "help"]
end
And in the view, you can write
<ul>
<% @pages.each do |p| %>
<li><%= link_to("#{p}", :controller => 'static_page', :action => "#{p}") %></li>
<% end %>
</ul>
Edit for the question in the comment
class StaticPagesController < ApplicationController
before_filter :load_pages, :only => [:about, :home, :help]
``` All your controller codes ```
private
def load_pages
@pages = ["load", "about", "help"]
end
end
So that all the methods in the :only
list will have @pages loaded before rendering the page. You don't have to load it in each method. you can declare the method in the ApplicationController
by writing a private before it like I did it here and just call it in any controller with the before_filter
.