Ruby on Rails - Add condition on ':include =>' to load limited number of objects

前端 未结 2 1723
南旧
南旧 2021-01-18 14:41

I have two models User and Event. The cardinality is one User has many Events. When I query the database to give me all the users and their corresponding events it returns t

2条回答
  •  北荒
    北荒 (楼主)
    2021-01-18 15:23

    Something along these lines should work:

    # Rails 3
    User.includes(:events).where(:events => {:created_at => Time.now.midnight..Time.now.tomorrow.midnight})
    
    # Rails 2
    User.find(:all, :includes => :events, :conditions => ["events.created_at between ? and ?", Time.now.midnight, Time.now.tomorrow.midnight])
    

    Time.now.tomorrow.midnight is pretty nasty. 1.day.from_now.midnight may be slightly less nasty, depending on your preference ;)

提交回复
热议问题