我正在尝试 link_to
show
操作以获取 post
。
在我的 Controller
中我有:
@post = Post.all
在我看来,我正在尝试将它链接到上一篇文章,如下所示:
<%= link_to @post.last do %>
<%= @post.last.title %>
<% end %>
但它不会将我带到该帖子的显示页面?
最佳答案
Post.all
加载所有帖子,但不保证顺序。您可能希望使用 id
或 created_at
值来对您的帖子列表进行排序:
# in your controller
@posts = Post.order(:id)
# in the view:
<%= link_to @posts.last.title, @posts.last %>
或者 - 如果您不需要 View 中的其他帖子 - 只需加载最新的帖子:
# in the controller:
@latest_post = Post.order(:id).last
# in the view:
<%= link_to @latest_post.title, @latest_post %>
关于ruby-on-rails - 链接到最后一篇文章 - rails,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38292428/