In my Rails app I allow users to "vote" on events. Some events are one specific date only and some events are ongoing.
I am trying to build a query that renders all the events that either A) a user has not voted on OR B) the ongoing events a user has voted on over 1 month ago.
Event has a "ongoing" boolean column. Event has_many votes. And User has_many votes.
Here's my query to get all the events a user has not voted on. It works.
scope :unvoted, ->(user_id) {
joins(
"LEFT OUTER JOIN votes ON votes.event_id = events.id AND " +
"votes.user_id = #{user_id}"
).where("votes.id IS NULL")
}
I am trying to add the or part of the query. I need to include "ongoing" events that the user has voted on over a month ago. Here's what I tried:
scope :unvoted, ->(user_id) {
joins(
"LEFT OUTER JOIN votes ON votes.event_id = events.id AND " +
"votes.user_id = #{user_id}"
)
.where(
"votes.id IS NULL OR events.ongoing = ? AND MAX(votes.created_at) < ?", true, 1.month.ago
)
}
But this is giving me the error:
PG::GroupingError: ERROR: aggregate functions are not allowed in WHERE
So I tried this:
scope :unvoted, ->(user_id) {
joins(
"LEFT OUTER JOIN votes ON votes.event_id = events.id AND " +
"votes.user_id = #{user_id}"
).
having('votes.id IS NULL OR events.ongoing = ? AND MAX("votes"."created_at") < ?', true, 1.month.ago).
group("events.id")
}
But this is giving me the error:
ERROR: column must appear in the GROUP BY clause or be used in an aggregate function
What's the proper query that I'm looking for?