Reinier Reinier - 4 months ago 17
Ruby Question

Join with where clause that filters out specific records, rails active record

I am making a sports application with leagues and events, the events contain a

league_id
, the leagues have a
name
and an
country_name
. How can I get all the event with starting date today together with the league name and country.

I tried:

League.joins(:events).where(events: {event_start: Time.zone.now..Time.zone.now.end_of_day})


But this returns all the leagues that have an event today, when I then try to access the events from that specific league, all events are included and not only the ones that are being plaid today.

Answer

Start with Events and include relevant League to avoid N+1 problem.

Event.includes(:league).where(event_start: Time.zone.now..Time.zone.now.end_of_day)