有效记录 - 获取不存在关联的记录

问题描述:

我有一个模型A其中has_many是我的B模型(所以B模型引用A的外键a_id)。 我想获得所有未被任何B记录引用的A记录。使用活动记录更有效的方法是哪种? 谢谢!有效记录 - 获取不存在关联的记录

细节可能取决于你的数据库,你创建的索引和数据存储但我建议你给子查询一试:

A.where.not(id: B.select(:a_id)) 

在PostgreSQL的,这将导致像单查询

SELECT * FROM as WHERE id NOT IN (SELECT a_id FROM bs) 
+0

Th正是我所需要的!我们很快就会接受答案。谢谢 –

+0

谢谢@RonanLopes!如果查询结果太慢,请发布更新,我很乐意帮助您调整它。 :-) –

由于导轨5的:

A.left_outer_joins(:bs).where(bs: { a_id: nil }) 

的在SQL的输出为:

SELECT "as".* FROM "as" 
LEFT OUTER JOIN "bs" ON "bs"."a_id" = "a"."id" 
WHERE "bs.a_id" IS NULL 
+0

这里的基准https://stackoverflow.com/a/45574301/2009803 – olimart

我在想你你的模型看起来像

class A < ApplicationRecord 
    has_may :bs 
end 

class B < ApplicationRecord 
    belongs_to :a 
end 

我想到你的schema.rb看起来像

create_table "as", force: :cascade do |t| 
    t.integer "id" 
    t.datetime "created_at", null: false 
    t.datetime "updated_at", null: false 
    end 

    create_table "bs", force: :cascade do |t| 
    t.integer "id" 
    t.integer "a_id" 
    t.datetime "created_at", null: false 
    t.datetime "updated_at", null: false 
    end 

,如果我有这那么你应该可以做

A.where.not(id: B.select(:a_id))