如何重构ActiveRecord查询?

y.b*_*gey 3 refactoring activerecord ruby-on-rails

我在控制器中有一个代码:

def latest
  @latest_articles = user_signed_in? ? Article.limit(10).order(id: :desc).pluck(:id, :title) : Article.where("status = ?", Article.statuses[:public_article]).limit(10).order(id: :desc).pluck(:id, :title)
  render json: @latest_articles
end
Run Code Online (Sandbox Code Playgroud)

如何重构它看起来优雅?我尝试使用lambda:

extract = lambda {|a| a.order(id: :desc).pluck(:id, :title)}
Article.limit(10) {|a| a.extract}
Run Code Online (Sandbox Code Playgroud)

但它只返回 Article.limit(10)

UPD:如果用户已登录,我需要获得所有文章的最后10篇,如果没有,我需要获得最后10篇文章.

Yur*_*dev 7

我会创建一个初始范围,并根据一些条件进行修改:

def latest
  scope = Article.order(id: :desc)
  scope = scope.where(status: Article.statuses[:public_article]) if user_signed_in?

  render json: scope.limit(10).pluck(:id, :title)
end
Run Code Online (Sandbox Code Playgroud)