Honestly I'm not even sure how to describe it in a single sentence, so that title might be way off. Here's what I'm trying to do:
I've got a fairly simple model. User -> Stories -> Comments. That is, a User has_many Stories, and a Story has_many Comments.
What I'm trying to do is only return the stories that:
- Have comments
- Were either created by the current user or have been commented on by the current_user
- But not if the开发者_运维知识库 current user is the only user to comment on it
What I have so far is:
Story.includes(:comments).where("stories.user_id = ? OR comments.user_id = ?", current_user.id, current_user.id)
But I have no idea how to do the last condition in SQL. The only thing I could do was use Enumerable methods.
@stories.reject! { |story| story.comments.collect(&:user_id).all? { |user_id| user_id == current_user.id }}
Sounds like you want to have a nested subquery, something like
Story.includes(:comments).where("stories.user_id = ? OR comments.user_id = ?)
and exists (select 'x' from comments c2 where c2.story_id = stories.id
and c2.user_id != ?)",
current_user.id, current_user.id, current_user.id)
精彩评论