Search code examples
ruby-on-railsrails-activerecordjoinvoting

Rails sort by count and time of a join table


I'm using acts_as_votable for my activities model and I've been able to select only the activities that have votes on them with the following code:

@activities = Activity.select("activities.*, COUNT(votes.id)").joins(:votes).group("activities.id").order("created_at desc").page(params[:page]).per_page(72)

But how do I select activities that only have for example greater than 3 votes and only the ones created within the last month?

Does anyone know how I could accomplish this? Thanks in advance.


Solution

  • having was what I was looking for. So for example:

    @activities = Activity.joins(:votes).group("activities.id").having("count(votes.id) >= ?", 1).order("created_at desc").where(:created_at => 6.months.ago..Time.zone.now.to_date).page(params[:page]).per_page(60)