Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/68.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
Ruby on rails 获取集合中包含的所有活动记录对象_Ruby On Rails_Ruby_Activerecord_Eager Loading - Fatal编程技术网

Ruby on rails 获取集合中包含的所有活动记录对象

Ruby on rails 获取集合中包含的所有活动记录对象,ruby-on-rails,ruby,activerecord,eager-loading,Ruby On Rails,Ruby,Activerecord,Eager Loading,是否有任何方法可以获取活动关系查询中包含的所有对象? 大概是这样的: def index @items = Item.all.includes(:comments) @comments = @items.comments // No such method for AR Collection :( end @comments = Comment.where(item_id: Item.pluck(:id)) 在这种情况下,获取所有项目的明显方式是: @comments = @item

是否有任何方法可以获取活动关系查询中包含的所有对象? 大概是这样的:

def index
  @items = Item.all.includes(:comments)
  @comments = @items.comments // No such method for AR Collection :(
end
@comments = Comment.where(item_id: Item.pluck(:id))
在这种情况下,获取所有项目的明显方式是:

@comments = @items.map(&:comments).flatten.uniq

由于使用了
.includes(:comments)
应该没有N+1查询,但我担心这段代码的性能。是否有任何内置的或更有效的方法来获取所有包含的收集记录?

您可以请求这样的评论:

def index
  @items = Item.all.includes(:comments)
  @comments = @items.comments // No such method for AR Collection :(
end
@comments = Comment.where(item_id: Item.pluck(:id))

您可以这样请求评论:

def index
  @items = Item.all.includes(:comments)
  @comments = @items.comments // No such method for AR Collection :(
end
@comments = Comment.where(item_id: Item.pluck(:id))

为什么要将所有注释放在一个单独的对象中
@comments
?您将如何准确地使用它?这实际上取决于您打算如何处理
@comments
-您是否需要按特定顺序使用它们?为什么要将所有注释放在一个单独的对象
@comments
?您将如何准确地使用它?这实际上取决于您打算如何处理
@comments
-您是否需要按任何特定顺序使用它们?您可以在一个查询中使用
@comments=Comment.where.not(item\u id:nil)
来执行相同的操作,如果您只关心它是否附加到某个项目上,我不建议这样做。您可以执行两个查询,其中一个查询可以轻松完成,但您将获得ActiveRecord集合,而不是纯数组,就像在问题的示例中一样,您可以使用
@comments=Comment.where.not(item\u id:nil)
在一个查询中执行相同的操作,如果只关心它是否附加到一个项,我不建议这样做。您可以执行两个查询,其中一个查询可以轻松完成,但您将得到ActiveRecord集合,而不是纯数组,如本例所示