User has many comments and comments belong to user. Comment table has status column which is boolean type.
Now I want to get users whose last comment has status true.
How can this be done in ActiveRecord query?
User has many comments and comments belong to user. Comment table has status column which is boolean type.
Now I want to get users whose last comment has status true.
How can this be done in ActiveRecord query?
You could try this query (get users those last comment has status true)
User.joins(:comments)
.where('comments.created_at = (SELECT MAX(comments.created_at) FROM comments WHERE comments.user_id = users.id)')
.where('comments.status = true')
.group('users.id')
This actually requires a sub query, so the idea is first fetching out all users last comment and filtering out with status as true to find out the users id with help of join.
Then
Otherwise use a join, will give you all the fields from User and Comment for every result.