我刚开始在我的Rails应用程序中使用局部模板,此刻我有下面的代码在我application.html.erb动态数据
<%= render 'categories/categorieslist' %>
此链接_categorieslist.html .erb在我的意见/类别/文件夹
目前这部分包含硬编码的超链接
<ul class="unstyled">
<li style="padding-bottom:5px"><a href="#">Item A»</a></li>
<li style="padding-bottom:5px"><a href="#">Item B»</a></li>
</ul>
我的目标是让这些类别来自数据库,如
<ul class="unstyled">
<% @categories.each do |category| %>
<li style="padding-bottom:5px"><a href="#"><%= category.name %> » </a></li>
<% end %>
</ul>
我试图在类别控制器如
def categorieslist
@categories = Category.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: @categories }
end
end
添加categorieslist方法,但这种不会被调用的部分(我不觉得这是连做正确的方法它),并呈现出就行了<%@ categories.each错误
NoMethodError in Store#index
做|类别| %>
我的问题是我如何传递到application.html.erb文件中的部分,这些类别对象通常来自类别控制器中的控制器方法?
任何帮助将是伟大的。
谢谢,我不太清楚的一件事是如何安排代码,以便传入此部分的@ categories集合通过调用@ categories = Category.all来填充,此activerecord查询的位置应该放在哪里代码,如果部分是在布局文件application.html.erb中? – norbert 2012-01-10 07:58:27
如果它在application.html.erb中,它应该放到你的ApplicationController中。在这里,你可以使用before_filter和def'get_cats @categories = Category.all end'这样的方法,或者你可以用'<%= render'categories/categorieslist'直接调用方法(它返回方法中的最后一个值) ,:all_categories => get_cats%>' – 2012-01-10 08:44:42
这太好了,我不确定是否有可能在ApplicationController中包含这样的东西,并没有找到任何明确的例子,谢谢! – norbert 2012-01-10 09:09:01