2011-05-02 48 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