Rails has_many通过查询

Rails has_many through query

我与用户、附件和表单模型之间存在多对多关系。

我想访问不属于用户的附件。我会尝试类似的方法,但没有用。

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

Update:

我还在寻找答案

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

正在工作,但 where.not returns 为空

我觉得where.not只看表格相关的附件,不是全部

其实很简单:

您需要的第一个(子)查询是获取用户 拥有的所有附件:

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

然后您可以轻松地从子查询中获取所有没有 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" = 
  ))