# How to get some eager loading to work

**URL:** <https://www.ruby-forum.com/t/how-to-get-some-eager-loading-to-work/144984>\
**Category:** Rails\
**Created:** [August 4, 2008, 11:26pm UTC](https://www.ruby-forum.com/t/how-to-get-some-eager-loading-to-work/144984 "2008-08-04T23:26:21Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![elioncho](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/e/ed8c4c/32.png) [@elioncho](https://www.ruby-forum.com/u/elioncho)\
**Post date:** [August 4, 2008, 11:26pm UTC](https://www.ruby-forum.com/t/how-to-get-some-eager-loading-to-work/144984/1 "2008-08-04T23:26:21Z")

</div>

Hello,

I am working on a query for the index action of a events\_controller. I  
fetch all the events followed by two methods which fetch for the users  
and the event\_categories related to the @events collection:

@events = Event.paginate\_by\_sql(“SELECT DISTINCT events.id,  
events.start\_date, events.title, events.place, events.user\_id,  
events.event\_category\_id  
FROM events INNER  
JOIN attendances ON attendances.event\_id = events.id  
WHERE  
(events.neighborhood\_id = 1) AND ((events.private = 0) OR  
(events.private = 1 AND attendances.user\_id = 1))  
ORDER BY  
events.created\_at DESC”, :page =\> params[:page], :per\_page =\>  
10)

# This two methods do the eager loading of users who created the

event and the category name of the event

User.find :all, :select =\> “users.id as users\_id, users.name as  
users\_name, users.lastname, users.neighborhood\_id”, :conditions =\>  
[“id in (?)”, @events.collect(&:user\_id)]

EventCategory.find :all, :select =\>  
“event\_categories.name”, :conditions =\> [“id in (?)”,  
@events.collect(&:event\_category\_id)]

I know I somehow need to do something more to make this work on my  
view where I loop through the @events collection showing the title,  
description…and well the user name who created the event and the  
category name. That’s where I get lost. Can anyone tell me how to  
associate those eager loaded arrays of users and categories to each  
event on the loop? Right now I have something like this on my view. I  
don’t want those “event.event\_category.name” and other methods… to  
execute a query on each loop.

\<% for event in @events %\>

 \> \<%=h nice\_date(event.start\_date) %\> \<%= link\_to event.title, neighborhood\_event\_path(event.user.neighborhood,event) %\> \<%=h event.place %\> \<%= link\_to event.user.displayname, user\_path(event.user) %\> \<%=h event.event\_category.name %\> \<% end %\>

Many thanks,

Elioncho
