如何使用'each'方法从ActiveRecord对象数组中检索值数组?

时间:2021-09-13 18:00:03

I'm trying to perform this non-basic query with Rails :

我正在尝试使用Rails执行此非基本查询:

proj_repartitions = ProjRepartition.includes(:proj_contributions).find( proj_project.proj_charges.each{|pc| pc.proj_repartition_id} )

The point is I need to pass an array of 'ids' to the find method. I want to extract those 'ids' from an array of ActiveRecord objects where each of these is equipped with an 'id' attribute.

关键是我需要将'ids'数组传递给find方法。我想从一组ActiveRecord对象中提取那些“ID”,其中每个对象都配有一个'id'属性。

When I try on the Rails console:

当我尝试Rails控制台时:

proj_project.proj_charges.each{|pc| pc.proj_repartition_id}

I got exactly the same array as proj_project.proj_charges

我得到了与proj_project.proj_charges完全相同的数组

What am I doing wrong?

我究竟做错了什么?

=== UPDATE ===

===更新===

According to the answers, my definitive working code is:

根据答案,我的权威工作代码是:

proj_project.proj_charges.collect{|pc| pc.proj_repartition_id}

3 个解决方案

#1


1  

Instead of using each try map or collect - they should return an array.

它们应该返回一个数组,而不是使用每个try map或collect。

#2


1  

Each only executes the do block code for each item but doesn't "save" the return value.

每个只执行每个项目的do块代码,但不“保存”返回值。

Collect and Map executes the do block code for each item and the return value in an array.

Collect和Map执行每个项的do块代码和数组中的返回值。

hope that makes sense

希望有道理

#3


1  

proj_project.proj_charges.map(&:proj_repartition_id)

Short way of writing

简短的写作方式

proj_project.proj_charges.map{|pc| pc.proj_repartition_id}

#1


1  

Instead of using each try map or collect - they should return an array.

它们应该返回一个数组,而不是使用每个try map或collect。

#2


1  

Each only executes the do block code for each item but doesn't "save" the return value.

每个只执行每个项目的do块代码,但不“保存”返回值。

Collect and Map executes the do block code for each item and the return value in an array.

Collect和Map执行每个项的do块代码和数组中的返回值。

hope that makes sense

希望有道理

#3


1  

proj_project.proj_charges.map(&:proj_repartition_id)

Short way of writing

简短的写作方式

proj_project.proj_charges.map{|pc| pc.proj_repartition_id}