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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With