Rails has_many通过查询

时间:2015-08-27 11:45:01

标签: sql ruby-on-rails has-many-through

我与User,Attachment和Form模型有多对多的关系。

我希望覆盖不属于用户的附件。我会尝试这样的东西,但没有用。

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返回空

我认为在哪里。不只是查看与表单相关的附件而不是所有附件

1 个答案:

答案 0 :(得分:1)

实际上非常简单:

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

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" = $1
  ))