我正在使用 ruby on rails 创建一个博客应用程序。我能够允许用户添加帖子,但在页面顶部,首先创建的帖子首先出现。我希望最新的博客文章首先出现。我该怎么做呢?让我知道我需要在此处添加哪些代码文件。
我的文章 Controller
class ArticlesController < ApplicationController
def new
@article = Article.new
end
def index
@articles = Article.paginate(:page => params[:page], :per_page => 10)
end
def show
@article = Article.find(params[:id])
end
def create
@article = Article.new(article_params)
@article.save
redirect_to @article
end
def edit
@article = Article.find(params[:id])
end
def update
@article = Article.find(params[:id])
if @article.update(article_params)
redirect_to @article
else
render 'edit'
end
end
def destroy
@article = Article.find(params[:id])
@article.destroy
redirect_to articles_path
end
end
private
def article_params
params.require(:article).permit(:title, :text, :datee)
end
最佳答案
我会在模型中设置一个默认范围,您可以只使用 order
但这是我喜欢的方式,因为我通常总是希望应用该顺序,这样我就不必继续使用 order
。将其放入您的模型中,它应该会对它们重新排序。
文章.rb
# Scopes
default_scope {order(created_at: :desc)}
设置默认范围后,无需采取进一步操作,文章将默认为该顺序。
如果您不希望它始终默认为该顺序,您只需创建一个常规范围即可调用。
文章.rb
scope :recent_first, -> {order(created_at: :desc)}
然后在 Index 操作中您将使用
def index
@articles = Article.recent_first.paginate(:page => params[:page], :per_page => 10)
end
如果您真的只需要在一个点 order
中执行此操作,正如 Adam Lassek 在下面的评论中提到的那样,也可以。
def index
@articles = Article.order(created_at: desc).paginate(:page => params[:page], :per_page => 10)
end
关于ruby-on-rails - rails : How to make recent blog posts appear first,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45534212/