找到不是在许多-to-many关联的所有记录 [英] Find all records NOT in a many-to-many association

查看:103
本文介绍了找到不是在许多-to-many关联的所有记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Rails 3用ActiveRecord,我有2个模型(用户和任务)。在另一种模式,分配通过关联关系:这些模型用的has_many联系在了一起。我如何才能找到那些没有关联到一个特定用户的所有任务?

 类用户的LT;的ActiveRecord :: Base的
  的has_many:任务
  的has_many:任务:通过=> :任务
结束

一流的任务和LT;的ActiveRecord :: Base的
  的has_many:任务
  的has_many:用户:通过=> :任务
结束

课堂作业和LT;的ActiveRecord :: Base的
  belongs_to的:用户
  belongs_to的:任务
结束
 

解决方案

短'东经甜的:

  Task.all  -  user.tasks
 

避免加载用户的任务:

  Task.where('身份证不在(?)',user.task_ids)
 

我无法弄清楚如何与外办呢加入AR。

In Rails 3 with ActiveRecord, I have 2 models (Users and Tasks). These models are linked together with a has_many :through association on another model, Assignments. How can I find all Tasks that are NOT associated to a particular user?

class User < ActiveRecord::Base
  has_many :assignments
  has_many :tasks, :through => :assignments
end

class Tasks < ActiveRecord::Base
  has_many :assignments
  has_many :users, :through => :assignments
end

class Assignments < ActiveRecord::Base
  belongs_to :users
  belongs_to :tasks
end

解决方案

Short 'n sweet:

Task.all - user.tasks

Avoid loading user tasks:

Task.where('id not in (?)', user.task_ids)

I couldn't figure out how to do it with an outer join in AR.

这篇关于找到不是在许多-to-many关联的所有记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆