Zip*_*po9 1 ruby-on-rails ruby-on-rails-4
在我的页脚中,它位于布局下的部分_footer中,我想显示在我的应用程序上写的最后3篇文章.我收到了Undefined method each for nilClass for @articles我发送的错误
ArticlesController索引为
@articles=Article.order("created_at DESC").limit(3)
Run Code Online (Sandbox Code Playgroud)
我应该在哪里定义@articles以在我的整个应用程序中访问它?我试图将它放入应用程序控制器但仍然出现错误.
在我的_footer.html.erb中的应用程序布局中
<div class="col-md-3 md-margin-bottom-40">
<div class="posts">
<div class="headline"><h2>Latest Posts</h2></div>
<% @articles.each do |article| %>
<ul class="list-unstyled latest-list">
<li>
<a href="#"><%= article.title.titleize %></a>
<small><%= article.created_at.strftime("%B-%m-%Y") %></small>
</ul>
<% end %>
</div>
</div><!--/col-md-3-->
Run Code Online (Sandbox Code Playgroud)
在这里调用_footer partial:
<body>
<div class="wrapper">
<%= render "layouts/header" %>
<%= render 'layouts/messages' %>
<%= yield %>
<div class="container">
</div>
<%= render "layouts/footer"%>
Run Code Online (Sandbox Code Playgroud)
由于您希望@articles在每个页面中显示,您每次都必须分配它.为此,请将以下内容添加到您的ApplicationController:
class ApplicationController
before_action :load_articles
private
def load_articles
@articles = Article.order("created_at DESC").limit(3)
end
end
Run Code Online (Sandbox Code Playgroud)
然后@articles将在每个页面中提供,以便您的页脚可以工作.
您可以删除@articles您ArticlesController已分配的分配ApplicationController.但要注意不要分配其他东西@articles.
| 归档时间: |
|
| 查看次数: |
748 次 |
| 最近记录: |