I want to update all posts, where comment IDs
Post.includes(:comments).where(comments: {id: comment_ids}).update_all(status: 1)
ERROR: missing FROM-clause entry for table "comments"
When using update_all
association should be loaded with joins
instead of includes
. Because includes
loads associated items in another query, therefore
Post.joins(:comments).where(comments: {id: comment_ids}).update_all(status: 1)
should work as expected
Try this:
posts = Post.joins(:comments).where(comments: {id: comment_ids})
posts.update_all(status: 1)
You can also use inner query to identify posts which needs to be updated.
post_ids = Comment.where(id: comment_ids).select(:post_id) #creates query to select all posts ids
Post.where(id: post_ids).update_all(status: 1) #executes update query on all posts