Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/69.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 如何加速AR查询_Sql_Ruby On Rails_Ruby_Activerecord - Fatal编程技术网

Sql 如何加速AR查询

Sql 如何加速AR查询,sql,ruby-on-rails,ruby,activerecord,Sql,Ruby On Rails,Ruby,Activerecord,让我们看看下面的代码: users = [] User.find_each do |u| author = u.articles.where('some where statement').limit(1).try(:author) users << { user: u.name, author: author } end users users=[] User.find|u每个do|u| author=u.articles.where('somewhere语句')。限制(

让我们看看下面的代码:

users = []

User.find_each do |u|
 author = u.articles.where('some where statement').limit(1).try(:author)
 users << { user: u.name, author: author }
end

users
users=[]
User.find|u每个do|u|
author=u.articles.where('somewhere语句')。限制(1)。try(:author)

用户快速设置将是:

User.includes(articles: :author).joins(:articles).merge(Article.where('some where statement')).map do |u|
  { user: u.name, author: u.articles.first.author }
end

但是,将所有文章加载为只获取一篇文章是没有用的,因此,如果
'some where statement'
是固定的,则可以定义专用关系。

快速设置是:

User.includes(articles: :author).joins(:articles).merge(Article.where('some where statement')).map do |u|
  { user: u.name, author: u.articles.first.author }
end

但是,将所有文章加载到只获取一篇文章是没有用的,因此如果
'some where statement'
是固定的,那么您可以定义一个专用关系。

据我所知,您希望每个用户都有一篇文章。因此,
分组方式自然会出现在我的脑海中。按照这些思路应该可以做到:

articles = Article.includes(:user, :author).where(your_where_condition).group(:user_id)
users = articles.map{|a| { user: a.user.name, author: a.author }}

据我所知,你想要每个用户一篇文章。因此,
分组方式自然会出现在我的脑海中。按照这些思路应该可以做到:

articles = Article.includes(:user, :author).where(your_where_condition).group(:user_id)
users = articles.map{|a| { user: a.user.name, author: a.author }}

你的最终目标是什么?收集符合您条件的文章的作者?@SergioTulentsev我已经编辑了代码。目标是使用User.name和Author创建新数组。请看更新后的代码。你的最终目标是什么?收集符合您条件的文章的作者?@SergioTulentsev我已经编辑了代码。目标是使用User.name和Author创建新数组。请看更新的代码。