How to get some eager loading to work

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

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs