Rails: Show 5 recent posts, excluding recent posts

I want to show the most recent entry in the show view with the next five last messages in the sidebar.

I am currently showing the last post, but the sidebar has the same post with the next 4 last 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--> 

Thank you very much.

+6
source share
2 answers

Offset is what you want:

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

This will return messages 2-5, if you want 2-6, use the limit (5)

+11
source

Since they are ordered from the most recent to the oldest, try

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

Source: https://habr.com/ru/post/943556/


All Articles