0

I'm trying to build an array using inject. I expect consents to be an array of ParticipantConsent objects.

Each ParticipantConsent object can :have_many ParticipantConsentSample objects.

I expect sc to contain an array of arrays of ParticipantConsentSample objects associated with every ParticipantConsent object associated with a Participant.

consents = ParticipantConsent.where(:participant_id => @participant.id).all
sample_consents = consents.inject { |sc, c| sc << ParticipantConsentSample.where(:participant_consent_id => c.id).all }

Currently getting back the contents of consents when I check the contents of sample_consents. Where am I going wrong? Thanks.

3 Answers 3

3

Since you just want an array of arrays obtained from ParticipantConsentSample, you don't really want inject, you want map:

sample_consents = consents.map do |c|
  ParticipantConsentSample.where(:participant_consent_id => c.id).all
end
Sign up to request clarification or add additional context in comments.

Comments

3

try the below:

sample_consents = consents.inject([]) do |sc, c| 
  sc << ParticipantConsentSample.where(participant_consent_id: c.id).to_a
  sc
end

2 Comments

I cleaned up your code but you don't need an inject for a simple array. Just use a map.
No need for standalone sc line in the block, as it is returned from the previous line. Don't you love Ruby :)
2

If you want sample_consents to be an array, you need to initialize it as one using an argument to inject:

sample_consents = consents.inject([]) { |sc, c| ... }

1 Comment

This is a terrible example because it ignores the trap that new Ruby programmers can get caught in: the injected value must be the last line of the injection block.

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.