我有两个模型,Computer
和Ipv6Address
Computer belongs_to Ipv6Address
Ipv6Address has_one Computer
使用ActiveRecord,如何找到与Ipv6Addresses
无关联的所有Computer
的列表?
答案 0 :(得分:0)
ipv6address_id是计算机表中的外键
和
id是Ipv6Address_id表的PK
ids=Computer.select('Ipv6Address_id')
Ipv6Address.select('*').where('id not in (?)',ids)
这可能有用
答案 1 :(得分:0)
Ipv6Address.where('ipv6address_id = ?', nil)
答案 2 :(得分:0)
使用我的Where Exists gem:
# fast
Ipv6Addresses.where_not_exists(:computer)
基准测试显示,在大多数情况下,它比向Ruby提取ID数组并将其发送回数据库要快得多:
# slow
ids = Computer.distinct(:ipv6_address_id).map(&:ipv6_address_id)
Ipv6Address.where.not(id: ids)