0

I'm trying to perform this non-basic query with 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.

When I try on the Rails console:

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

I got exactly the same array as 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 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Great ! It work with 'collect'. I'm still wondering why it doesn't work with each...
each is just a way of looping but doesn't return anything whereas collect returns an array. Any chance of a best answer?
1

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

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

hope that makes sense

Comments

1
proj_project.proj_charges.map(&:proj_repartition_id)

Short way of writing

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.