Preload has_many associations with dynamic conditions

后端 未结 4 1992
旧巷少年郎
旧巷少年郎 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

    To solve the dynamic date problem, have you considered:

    class Event < ActiveRecord::Base
    
      belongs_to :place
    
      scope :on_date, lambda {|the_date| where(start_date: the_date) }
      scope :on_or_after, lambda {|the_date| where('start_date >= ?', the_date) }
    end
    

    You could then do this:

    @place = Place.find(params[:id]) # let's say...
    @place.events.on_date(params[:chosen_date])
    

    You can incorporate the eager loading stuff that others have mentioned too.

提交回复
热议问题