【问题标题】:Rails: Show 5 most recent posts excluding the most recent postRails:显示 5 个最近的帖子,不包括最近的帖子
【发布时间】:2013-04-24 16:45:18
【问题描述】:

我想在显示视图中显示最近的帖子,并在侧边栏中显示接下来的五个最新帖子。

目前,我显示最新的帖子,但侧边栏包含同一个帖子以及接下来的 4 个最新帖子。

控制器:

def show
  @post = Post.find(params[:id])
  @posts = Post.includes(:comments).order("created_at DESC").limit(5)
end

查看:

<div class="related-articles">
  <h2 class="headline">Related Articles</h2>
    <% @posts.each do |post| %>
      <div class="floatLeft"><%= link_to (image_tag post.image.url(:thumb)), post_path(post) %></div>
      <h2 class="headline smaller-font"><%= link_to post.title, post %></h2>
      <div class="image-remove"><%= raw truncate_html(post.body, length: 190) %>
      <%= link_to "read more", post %></p></div>
      <hr>

<% end %>

</div><!--related articles box--> 

非常感谢。

【问题讨论】:

    标签: ruby-on-rails controller views


    【解决方案1】:

    偏移量是你想要的:

    @posts = Post.includes(:comments).order("created_at desc").limit(4).offset(1)
    

    这将返回帖子 2-5,如果你想要 2-6 则使用 limit(5)

    【讨论】:

      【解决方案2】:

      由于它们是按最新到最旧的顺序排列的,请尝试

      @posts = Post.includes(:comments).order("created_at DESC").limit(6)
      @posts.slice!(0)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-07-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-12-15
        • 2015-11-17
        相关资源
        最近更新 更多