简体   繁体   English

如何在所有模型实例中获取所有has_many对象?

[英]How to get all has_many objects in all model instances?

I have the Event model. 我有Event模型。 It has_many :participants . 它有很多has_many :participants

Can do Event.all.each do |event| 可以做Event.all.each do |event| and then try to manipulate event.participants 然后尝试操纵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. 当你使用正确的方法得到一个“事件”数组而不是一个EventArray时,这是OO中的一个典型问题。

You can get Participants that are part of any Event like this 您可以获得属于此类Event Participants

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

or just 要不就

Participant.all

if there are no Participants without an associated Event 如果没有没有相关Event Participants

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

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

you can use eager_load and group_by in this issue. 您可以在此问题中使用eager_loadgroup_by 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. 您可以访问参与者的0索引和该事件的1个索引。 Something like 就像是

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何选择具有另一个对象实例的所有对象(has_many和has_one关联)? - How to select all objects that have instances of another object (has_many and has_one association)? 获取每个集合项的所有has_many实例 - Get all has_many instances for each collection item ActsAsTaggableOn:获取has_many关系中子对象的所有标签 - ActsAsTaggableOn: Get all tags for child objects in a has_many relation 如何通过关联获取has_many的所有项目 - how to get all items of has_many through association 获取所有has_many关联在rails中 - get all has_many associations in rails 通过多态类的关系从has_many获取所有相关实例 - Get all related instances from has_many through relationship of a polymorphic class 查找没有关联has_many对象的所有对象 - Find all objects with no associated has_many objects 如何查找其has_many通过对象包括某个列表的所有对象的记录? - How to find records, whose has_many through objects include all objects of some list? 如果用户有has_many辆汽车,而某车有has_many多个约会,我如何获得所有用户的约会? - If a user has_many cars, and a car has_many appointments, how can I get all of a users appointments? 查找模型上定义的所有:has_many关系 - Finding all the :has_many relationship defined on a model
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM