
[英]In Rails how to get the number of records which don't have children (has many association)?
[英]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
我需要从表 model_a 中获取所有在表model_a
中没有匹配记录的model_b
——无论是通过 AR 还是原始 PostgreSQL 查询。
最优雅/最有效的方法是什么?
我能想到的只是循环遍历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)
为了便于理解:
model_b_ids = ModelB.all.pluck(:id)
ModelA.where('model_b_id NOT IN (?)', model_b_ids)
您必须尝试对表 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 })
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.