[英]How do I query an association for non-unique values of a field with SQL/ActiveRecord?
老實說,我什至不知道如何用一句話來描述它,所以這個標題可能會離題。 這是我正在嘗試做的事情:
我有一個相當簡單的 model。 用戶 -> 故事 -> 評論。 也就是說,一個用戶有_many Stories,一個Story has_many Comments。
我要做的只是返回以下故事:
到目前為止,我所擁有的是:
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 }}
聽起來你想要一個嵌套的子查詢,比如
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.