我在 Controller 中有一个代码:
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
如何重构它看起来优雅? 我尝试使用 lambda:
extract = lambda {|a| a.order(id: :desc).pluck(:id, :title)}
Article.limit(10) {|a| a.extract}
但它只返回 Article.limit(10)
UPD:如果用户登录,我需要获取所有文章的最后 10 篇,如果没有,我需要获取最后 10 篇公开文章。
最佳答案
我会创建一个初始范围,并根据一些条件对其进行修改:
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
关于ruby-on-rails - 如何重构 ActiveRecord 查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31701247/