链接到最后的帖子 - rails

Gur*_*ngh 1 ruby ruby-on-rails ruby-on-rails-4

我试着去link_toshow一个行动post.

在我的controller身上:

@post = Post.all
Run Code Online (Sandbox Code Playgroud)

在我看来,我试图将它链接到最后一个帖子,如下所示:

<%= link_to @post.last do %>
 <%= @post.last.title %>
<% end %>
Run Code Online (Sandbox Code Playgroud)

但它没有带我到那篇文章的节目页面?

spi*_*ann 5

Post.all加载所有帖子,但不保证订单.您可能希望使用idcreated_at值来订购帖子列表:

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

# in the view:
<%= link_to @posts.last.title, @posts.last %>
Run Code Online (Sandbox Code Playgroud)

或者 - 如果您不需要视图中的其他帖子 - 只需加载最新帖子:

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

# in the view:
<%= link_to @latest_post.title, @latest_post %>
Run Code Online (Sandbox Code Playgroud)