Ruby on Rails - add a condition on: include => to load a limited number of objects

I have two models User and Event. Power - one user has many events. When I query the database to give me all the users and their corresponding events, it will return the correct results. Operator example: Users.find (: all ,: include => [: events])

However, I need help getting state-based events for the user. I need each User to return to receive only the events that are scheduled for today (for example: CREATED_DATE = TODAY). That is, I do not want all events related to Users. It is said that I still need all the users found in the database, but for some of those users who do not have an event planned for today, they should not have an Event loaded into the hash map.

Can someone help me with changing the "Users.find (: all ,: include => [: events])" Rails so that I can only receive specific events for users, not all events?

Thanks, S

+6
ruby ruby-on-rails
source share
2 answers

As far as I know, you cannot use the include: parameter as you describe.

What is the problem with getting all events? In any case, you will have to upload / join / query the event table. However, you need more memory if you trigger all events.

Of course, you could fulfill two queries: one for users with today events and one for those who donโ€™t.

You can also go in the opposite direction:

Event.find(:all, :conditions => "...only today...", :include => :user) 

That will give you all the events for today with the included users. You can use another query to get all users, not including events, and do everything else in memory.

+1
source share

Something in this direction 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 rather unpleasant. 1.day.from_now.midnight may be a little less unpleasant, depending on your preference;)

+6
source share

All Articles