简体   繁体   中英

How to get all has_many objects in all model instances?

I have the Event model. It has_many :participants .

Can do Event.all.each do |event| and then try to manipulate event.participants

But is there an easier way to get all participants for all events?

It's a typical problem in OO when you get an Array of "Events" back not an EventArray with the right methods.

You can get Participants that are part of any Event like this

Participant.where(event_id: Event.pluck(:id))

or just

Participant.all

if there are no Participants without an associated Event

Participant.joins(:event)应该让你参与一个活动。

Event.joins(:participants).select("participants.*")这将为所有与事件相关联的参与者提供

you can use eager_load and group_by in this issue. In your case

event = Event.eager_load(:participants).group_by(&:participants)

it will create a Hash of all events with associated participants. you can access 0 index for participants and 1 index for that event. Something like

event.first[0] = all the participants of that event
event.first[1] = that event

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM