Reputation: 706
In my footer, which is located in a partial _footer under layouts, I want to display the last 3 articles written on my app. I am getting the error Undefined method each for nilClass for @articles
which I have sent up in the
ArticlesController index as
@articles=Article.order("created_at DESC").limit(3)
Where should I define @articles to have access to it in my whole app? I have tried to put it into application controller but was still getting an error.
In my _footer.html.erb which in in Application layouts
<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-->
_footer partial is being called here:
<body>
<div class="wrapper">
<%= render "layouts/header" %>
<%= render 'layouts/messages' %>
<%= yield %>
<div class="container">
</div>
<%= render "layouts/footer"%>
Upvotes: 1
Views: 1208
Reputation: 61
First of all, if you want to show @articles in your websites footer you probably need set @articles for all controllers, not just ArticlesController, try setting @articles in ApplicationController:
before_filter :set_articles
private
def set_articles
@articles = Article.order("created_at DESC").limit(3)
end
Second step:
<body>
<div class="wrapper">
<%= render "layouts/header" %>
<%= render 'layouts/messages' %>
<%= yield %>
<div class="container">
</div>
<%= render "layouts/footer", locals: {articles: @articles} %>
</body>
and inside your footer partial use article instead of @articles
<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-->
More on partials: http://guides.rubyonrails.org/layouts_and_rendering.html#using-partials
Upvotes: 0
Reputation: 38842
Since you want to display @articles
in every page you're gonna have to assign it every time. To do so, add the following to your ApplicationController
:
class ApplicationController
before_action :load_articles
private
def load_articles
@articles = Article.order("created_at DESC").limit(3)
end
end
Then @articles
will be available in every page so your footer will work.
You can remove the assignation of @articles
from your ArticlesController
as it's already assigned by the ApplicationController
. Be careful not to assign something else to @articles
though.
Upvotes: 6
Reputation: 387
In your index.html.erb, you should render the partial and pass in @articles like so
<%= render 'layouts/footer', obj: @articles %>
In your footer partial, refer to @articles as obj. You can change obj to any name you want.
Upvotes: 0