Ruby 关于 Rails + PostgreSQL:如何从 table A 获取在 table B 中没有关联的所有记录?
Ruby On Rails + PostgreSQL: How to get all records from table A that don't have association in table B?
我有这两个型号:
class ModelA < ApplicationRecord
has_one :model_b
end
class ModelB < ApplicationRecord
belongs_to :model_a
end
而且我需要从 table model_a
中获取在 table model_b
中没有匹配记录的所有记录 - 无论是通过 AR 还是原始 PostgreSQL 查询。
最 elegant/efficient 的方法是什么?
我只能想到遍历 model_a
并在 model_b
中搜索匹配的记录。
提前致谢。
你试过LEFT JOIN
吗?像
ModelA.left_joins(:model_b).where(table_model_b: {model_a_id: nil})
如果我没看错你的想法,你可以尝试只排除具有关系的 ID
ModelA.where.not(id: ModelB.pluck(:model_a_id).uniq)
您必须在 table b.
中尝试在 A_id 上进行左连接和过滤
ModelA.left_joins(:ModelB).where("model_B.model_a_id": nil)
ModelA.left_joins(:ModelB).where(model_B: { model_a_id: nil })
为了便于理解:
model_b_ids = ModelB.all.pluck(:id)
ModelA.where('model_b_id NOT IN (?)', model_b_ids)
我有这两个型号:
class ModelA < ApplicationRecord
has_one :model_b
end
class ModelB < ApplicationRecord
belongs_to :model_a
end
而且我需要从 table model_a
中获取在 table model_b
中没有匹配记录的所有记录 - 无论是通过 AR 还是原始 PostgreSQL 查询。
最 elegant/efficient 的方法是什么?
我只能想到遍历 model_a
并在 model_b
中搜索匹配的记录。
提前致谢。
你试过LEFT JOIN
吗?像
ModelA.left_joins(:model_b).where(table_model_b: {model_a_id: nil})
如果我没看错你的想法,你可以尝试只排除具有关系的 ID
ModelA.where.not(id: ModelB.pluck(:model_a_id).uniq)
您必须在 table b.
中尝试在 A_id 上进行左连接和过滤ModelA.left_joins(:ModelB).where("model_B.model_a_id": nil)
ModelA.left_joins(:ModelB).where(model_B: { model_a_id: nil })
为了便于理解:
model_b_ids = ModelB.all.pluck(:id)
ModelA.where('model_b_id NOT IN (?)', model_b_ids)