简体   繁体   English

如何在Rails 4中仅显示帖子的部分标题?

[英]How to display section title for posts only once in Rails 4?

I'd like to list Posts based on their Section . 我想根据其Section列出Posts And I have written the given code: 我已经编写了给定的代码:

View 视图

<div class="right-links">
    <% @posts.each do |p| %>
        <h3 class="title">
            <%= p.section.title %>
        </h3>

        <p><%= link_to p.title, p %></p>
    <% end %>
    &nbsp;
</div>

Controller 调节器

@posts = Post.limit(15)

Obviously this isn't enough and all it does is it displays every post with its section title and that's not really what I want. 显然,这还不够,它所要做的就是显示每篇帖子及其标题,这并不是我真正想要的。 Is there some tutorial or maybe you guys can help me out how to display the section title only once and then all of the posts under it? 是否有一些教程,或者你们可以帮助我如何仅显示一次section title ,然后显示该section title下的所有帖子?

Thank you. 谢谢。

You can do this by using the group_by method in the controller. 您可以通过使用控制器中的group_by方法来执行此操作。

@sections_posts = Post.limit(15).group_by(&:section_id)

Then display it in the view 然后在视图中显示

<div class="right-links">
    <% @sections_posts.each do |section_id, posts| %>
        <h2 class="title">
            <%= Section.find(section_id).title %>
        </h2>

        <% posts.each do |post| %>
          <p><%= link_to post.title, post %></p>
        <% end %>
    <% end %>
    &nbsp;
</div>

That should do it for you. 那应该为你做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM