简体   繁体   English

Rails has_many检索所有记录

[英]Rails has_many retrieve all records

# Events
has_many :attendees

# Attendees
belongs_to :event

How can I access All the Events with each Event's Attendees? 如何与每个活动的参加者一起访问所有活动?
Event.all.attendees # obviously does not work

To do this for 1 event, we can do 为此1个活动,我们可以
Event.find(1).attendees
How can we do this for all events? 我们如何为所有活动做到这一点? Is there an automagic way or do we need a loop? 是否有一种自动的方法,还是需要循环?

Yes. 是。 there is. 有。 Have a read about AR query methods. 阅读有关AR查询方法的信息。

There are two main methods to look on: 有两种主要的查看方法:

joins and includes . joinsincludes

Event.includes(:attendees)

would load all events and it's attendees (whether there are any or none) 将加载所有事件,并且是与会者(无论有无)

Event.joins(:attendees)

would select those events, which have assigned attendees. 将选择已分配参加者的那些活动。

With both options you can then iterate over events' attendees with a block. 使用这两个选项,您都可以使用块来遍历活动的参加者。


Edit 编辑

Just a short clarification. 请稍作说明。 I do understand, that you probably needed a result, that can be ( but never should be ) achieved this way: 我确实知道,您可能需要一个结果,可以( 但绝不应该 )通过这种方式实现:

Event.all.map(&:attendees) # would return a collection of attendees.

Such queries are evil, since they are fully loaded into memory before execution. 这样的查询是邪恶的,因为它们在执行之前已完全加载到内存中。

And the point of edit - you would "never" actually need such thing, as loading a collection of assigned attendees. 编辑的重点-您实际上将不需要”任何东西,例如加载一组指定的与会者。

Why? 为什么?

Because if you ever need a collection of attendees, operate on Attendee model, not Event or any other associated model. 因为如果您需要与会者集合,请使用“ Attendee模型而不是“ Event或任何其他关联模型进行操作。

What that mean, is that you can get some events meeting certain condition(s). 这意味着您可以获得一些满足特定条件的事件。

For example: 例如:

events = Event.where('start_date > ?' Date.today)

If you need Attendees for this event, you would rather do this 如果您需要参加此活动的与会者,则宁愿这样做

Attendee.where(event_id: events.ids)

then this 然后这个

Event.where('start_date > ?' Date.today).map(&:attendees) #inefficient

I hope I made myself clear. 我希望我能说清楚。

You can use eager loading to retrieve the Event and their associated Attendee in few SQL queries: 您可以使用紧急加载在一些SQL查询中检索事件及其关联的与会者:

events = Event.includes(:attendees)
events.each do |event|
  event.attendees
end

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

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