Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: Show 5 most recent posts excluding the most recent post

I want to show the most recent post in the show view, with the next five most recent posts in the sidebar.

Currently, I show the most recent post, but the sidebar includes that same post with the next 4 most recent posts.

Controller:

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

View:

<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--> 

Thanks very much.

like image 222
user2299459 Avatar asked Apr 24 '13 16:04

user2299459


1 Answers

Offset is what you want:

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

This will return posts 2-5, if you want 2-6 then use limit(5)

like image 75
Shawn Balestracci Avatar answered Sep 28 '22 17:09

Shawn Balestracci