在页脚轨道中显示动态内容

时间:2015-04-08 03:23:20

标签: 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)

我应该在哪里定义@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-->

在这里调用_footer partial:

    <body>
<div class="wrapper">
 <%= render "layouts/header" %>

 <%= render 'layouts/messages' %>
 <%= yield %>
 <div class="container">
 </div>
 <%= render "layouts/footer"%>

3 个答案:

答案 0 :(得分:6)

由于您希望在每个页面中显示@articles,因此您每次都必须分配它。为此,请将以下内容添加到ApplicationController

class ApplicationController
  before_action :load_articles

private

  def load_articles
    @articles = Article.order("created_at DESC").limit(3)
  end

end

然后@articles将在每个页面中显示,以便您的页脚可以正常工作。

您可以从@articles移除ArticlesController的{​​{1}}分配,因为ApplicationController已经分配了@articles。但请注意不要将其他内容分配给{{1}}。

答案 1 :(得分:0)

在index.html.erb中,你应该渲染部分并传入@articles,如此

<%= render 'layouts/footer', obj: @articles %>

在你的页脚部分中,将@articles称为obj。您可以将obj更改为您想要的任何名称。

答案 2 :(得分:0)

首先,如果您想在网站页脚中显示@articles,您可能需要为所有控制器设置@articles,而不仅仅是ArticlesController,尝试在ApplicationController中设置@articles:

before_filter :set_articles

private
  def set_articles
    @articles = Article.order("created_at DESC").limit(3)
  end

第二步:

<body>
  <div class="wrapper">
  <%= render "layouts/header" %>

  <%= render 'layouts/messages' %>
  <%= yield %>
  <div class="container">
  </div>
  <%= render "layouts/footer", locals: {articles: @articles} %>
</body>

并在页脚内部使用文章而不是@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-->

更多关于部分内容: http://guides.rubyonrails.org/layouts_and_rendering.html#using-partials