2015-08-27 87 views
0

我與用戶,附件和表單模型有多對多的關係。Rails has_many通過查詢

我想達到不屬於用戶的附件。我會嘗試這樣的事情,但沒有奏效。

Attachment.includes(:forms,:users).where.not('forms.user_id = ?', @user.id).references(:forms,:users) 

我已經嘗試了更多,但沒有找到正確的。

user.rb

has_many :forms 
    has_many :attachments, through: :forms 

attachment.rb

has_many :forms 
    has_many :users, through: :forms 

forms.rb

belongs_to :user 
    belongs_to :attachment 

更新:

我還在原地找到答案

Attachment.includes(:forms).where(forms: {user_id: user.id}).references(:forms) 

是工作,但where.not返回空

我覺得where.not不僅看起來相關附件以形成並非全部

+0

你能告訴你的模型的實際關聯? – IngoAlbers

+0

我編輯了問題 –

回答

1

它的其實很簡單:

第一(子)查詢你需要的是讓所有的用戶確實的附件有:

subquery = @user.attachments.select(:id) 

然後你就可以輕鬆搞定所有的附件唐't擁有來自子查詢的id。

Attachment.where.not(subquery) 
# same as 
Attachment.where.not(@user.attachments.select(:id)) 

以領先的查詢:

SELECT "attachments".* 
    FROM "attachments" 
    WHERE ("attachments"."id" NOT IN (
    SELECT "attachments"."id" 
    FROM "attachments" 
    INNER JOIN "forms" 
    ON "attachments"."id" = "forms"."attachment_id" 
    WHERE "forms"."user_id" = $1 
)) 
+0

您是否設法找到錯誤?此外,我會刪除我的評論,他們是一團糟,不會爲未來的讀者服務 - 你也應該 –

+0

我還在等待,我會了解更多關於查詢,我希望我會管理 –