Preload has_many associations with dynamic conditions

后端 未结 4 1993
旧巷少年郎
旧巷少年郎 2020-12-15 08:24

I have a Place model and an Event model. Places can have events that take place on a specific date.

How can I set up my associatio

4条回答
  •  旧巷少年郎
    2020-12-15 08:37

    As I understand, you want to fetch all the places that has at least one event satisfying some condition, but places should be fetched with all events list even those which doesn't satisfy condition. You can't figure this is out with one simple query, but if you will use suquery then issue will done. Here is the solution:

    Place.includes(:events).where(id: Place.joins(:events).where("events.start_date > '#{time_in_the_future}'")).references(:events)
    

    There is one complex query will be constructed, but it do the things right.

提交回复
热议问题