2011-05-02 41 views
0

老实说,我甚至不确定如何用一个句子来描述它,所以标题可能会有所改变。这是我想要做的:如何使用SQL/ActiveRecord查询关于字段的非唯一值的关联?

我有一个相当简单的模型。用户 - >故事 - >评论。也就是说,一个用户has_many的故事,和一个故事has_many的评论。

我试图做的是只返回故事:

  • 有意见
  • 要么由当前用户创建或由CURRENT_USER已经谈到
  • 但如果当前用户是用户就可以

我至今是评论:

Story.includes(:comments).where("stories.user_id = ? OR comments.user_id = ?", current_user.id, current_user.id) 

但我不知道如何做SQL中的最后一个条件。我唯一能做的就是使用Enumerable方法。

@stories.reject! { |story| story.comments.collect(&:user_id).all? { |user_id| user_id == current_user.id }} 

回答

1

听起来像是你想有一个嵌套子查询,像

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) 
+0

嗯,我试过了,但它似乎没有工作... – 2011-05-03 03:21:47

+0

呵呵,或组缺少括号。 “(stories.user_id =?OR comments.user_id =?)AND EXISTS(从评论c2中选择'x',其中c2.story_id = stories.id和c2.user_id!=?)” – 2011-05-03 03:29:25