列出与当前activerecord对象无关的数据

时间:2019-02-04 09:15:43

标签: ruby-on-rails activerecord

class Group < ApplicationRecord
  has_many :group_tests

  has_many :tests, through: :group_tests
end

class GroupTest < ApplicationRecord
  belongs_to :group
  belongs_to :test
end

class Test < ApplicationRecord
  has_many :group_tests
  has_many :groups, through: :group_tests
end

我有这个数据库设计。我只需要列出未添加到组中的那些测试。

假设我们有6个测试(测试1,测试2,测试4 ....)和3个组(第1组,第2组,第3组)

我们将3个测试(测试1,测试2,测试3)添加到第1组。

现在我只想获取组1中不存在的那些测试,即测试4,测试5,测试6

group = Group.find(id) // lets say group 1
// find tests that are not added to this group 

2 个答案:

答案 0 :(得分:1)

您可以将其写成一行。

Test.left_outer_joins(:groups).where.not(groups: {id: id})

答案 1 :(得分:1)

首先,您找到属于特定组的测试ID,然后使用not,也可以通过联接使用@Vasilisa查询。

group_test_ids = group.tests.ids #test ids which belongs to group

tests = Test.where.not(id: group_test_ids) # tests which not contain that group

一支班轮

tests = Test.where.not(id: group.tests.ids)