RoR 如何设置根以显示模型中的最新条目

RoR How to set the root to show the latest entry in a model

已经研究并看到了很多使用 Post.order("created_at").last 之类的方法来检索模型中最新条目的方法,但未能成功地将其作为网页的根目录。

只需将根设置为 PostsController 上的自定义操作,并让其为您处理。例如:

routes.rb

root 'posts#show_latest'

posts_controller.rb

def show_latest
  @post = Post.order("created_at").last
  render :show
end