简体   繁体   中英

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.

Event s开始,并包括相关的League以避免N + 1问题。

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

To get all the event with starting date today, I think you need to search between beginning_of_day to end_of_day

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

or

Event.includes(:league).where("event_start >= ? && event_start <= ?", Time.zone.now.beginning_of_day, Time.zone.now.end_of_day)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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