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
- 是由当前用户创建的,还是由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.
但是我不知道如何在SQL中执行最后一个条件。我唯一能做的就是使用可枚举的方法。
@stories.reject! { |story| story.comments.collect(&:user_id).all? { |user_id| user_id == current_user.id }}
1 个解决方案
#1
1
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)
#1
1
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)