Rails Has Many Active Record Query

510 views Asked by At

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?

3

There are 3 answers

1
Fabrizio Bertoglio On
@user_ids = Comment.where(status: true).pluck(:user_id)

Then

User.where(id: @user_ids)

Otherwise use a join, will give you all the fields from User and Comment for every result.

Comment.joins(:user).where(user_id: @user_ids)
3
Sachin R On
users = []
User.all.each do |user|
  users << user if user.comments && user.comments.last.status
end

users # list of all user whose last comment status = true

users object consist all the users whose last comment status is true.

0
Ashik Salman On

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.