0

我正在尝试使用注入构建一个数组。我希望consents成为一个ParticipantConsent对象数组。

每个ParticipantConsent对象都可以:have_many ParticipantConsentSample对象。

我希望sc包含一个对象数组,这些ParticipantConsentSample对象数组ParticipantConsent与与Participant.

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

目前,consents当我检查sample_consents. 我哪里错了?谢谢。

4

3 回答 3

3

试试下面的:

sample_consents = consents.inject([]) do |sc, c| 
  sc << ParticipantConsentSample.where(participant_consent_id: c.id).to_a
  sc
end
于 2013-05-17T17:06:13.853 回答
3

由于您只想要从 ParticipantConsentSample 获得的数组数组,因此您并不真正想要inject,您想要map

sample_consents = consents.map do |c|
  ParticipantConsentSample.where(:participant_consent_id => c.id).all
end
于 2013-05-17T17:37:57.337 回答
2

如果你想sample_consents成为一个数组,你需要使用一个参数将它初始化为一个inject

sample_consents = consents.inject([]) { |sc, c| ... }
于 2013-05-17T17:06:05.180 回答