1

I have a User model and an Event model. User has_many events. What I want to be able to do is find the User that has the most events created in the last 24 hours.

Ideally, the output format would have be an array of hashes [{User => [Event, Event, ...]}], which would be sorted by User's with the highest events.count

Thanks

1

1 Answer 1

1

This works for me, but might require tweaking depending on your database.

class User
  scope :by_most_events, -> { 
    joins(:events)
    .select("users.*, count(events.id) as event_count")
    .where(events: { created_at: 24.hours.ago..Time.now })
    .group("users.id, events.id") # this is for postgres (required group for aggregate)
    .order("event_count desc")
  }
end

### usage

User.by_most_events.limit(1).first.event_count
# => 123

As Sixty4Bit mentioned, you should use counter_cache, but it will not suffice in this situation because you need to query for events created in the last 24 hours.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.