Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 the right results. Example statement: Users.find(:all, :include=>[:events])

However, what I need help with is to get events for a user based on a condition. I need for each User returned to get only Events that are scheduled for today (ex: CREATED_DATE = TODAY). That is, I don't want all events associated to Users. Said that, I still need all Users found in the database, but for some of those users that don't have an Event scheduled for today, they should not have an Event loaded in the hash map.

Can someone please help me with modifying "Users.find(:all, :include=>[:events])" Rails statement so I can get only certain Events for Users, not all Events?

Thanks, S

like image 324
partizan Avatar asked Dec 15 '10 19:12

partizan


2 Answers

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 ;)

like image 94
idlefingers Avatar answered Oct 18 '22 20:10

idlefingers


To my knowledge, you can't use the :include option in the way you describe.

What is your problem with getting all the events anyway? You will have to load/join/query the events table anyway. You will need more memory, though, if you instanciate all events.

Of course you could do two queries, one for the users with the events "today", and one for those without.

You could also go the other way round:

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

Which would give you all events for today with users included. You can use another query to get all users without including the events, and do the rest in memory.

like image 23
averell Avatar answered Oct 18 '22 20:10

averell