在conrails index API中使用concat

问题描述 投票:0回答:1

我正在使用一个我希望在单个数组中具有不同状态的数据的api。

def filter_index_by_admin
  articles = []
  articles.concat(Article.pending.map { |article| ArticlePresenter.new(article)._show})
  articles.concat(Current.user.articles.where(status: 'approved').map { |article| ArticlePresenter.new(article)._show})
  articles.concat(Current.user.articles.where(status: 'rejected').map { |article| ArticlePresenter.new(article)._show})
  articles.concat(Current.user.articles.where(status: 'saved').map { |article| ArticlePresenter.new(article)._show(user_included: true, comments_included: true)})
  render json: { articles: articles }, status: :ok                                          
end

在上面的api中,命名文章中有一个数组,其中我正在整理数据在第三行中,我获取由所有用户创建的状态为待审核的所有文章的索引。

在第四行中,我将当前用户的文章的状态为已批准,在第五行中的状态为已拒绝,第六行中的状态为保存

我知道这不是肮脏的代码。

所以,有什么办法可以用复杂的方式做到吗?

ruby-on-rails concat
1个回答
0
投票

您可以这样做:

articles = Current.user.articles.where(status: ['pending', 'rejected', 'approved', 'saved']).map { |article| ArticlePresenter.new(article)._show})

更新

如果您使用的是Rails 5 +

articles = Article.where(user_id: Current.uer.id, status: ['rejected', 'approved', 'saved']).or(Article.pending).map { |article| ArticlePresenter.new(article)._show})
© www.soinside.com 2019 - 2024. All rights reserved.