Gurmukh Singh Gurmukh Singh - 4 months ago 21
Ruby Question

link to last post - rails

Im trying to

link_to
the
show
action for a
post
.

In my
controller
I have:

@post = Post.all


In my view I'm trying to link it to the last post like this:

<%= link_to @post.last do %>
<%= @post.last.title %>
<% end %>


But it does not take me to the show page for that post?

Answer

Post.all loads all posts, but does not guarantee an order. You might want to use the id or the created_at value to order your list of posts:

# in your controller
@posts = Post.order(:id)

# in the view:
<%= link_to @posts.last.title, @posts.last %>

Or - if you don't need the other posts in the view - just load the lastest post:

# in the controller:
@latest_post = Post.order(:id).last

# in the view:
<%= link_to @latest_post.title, @latest_post %>