Ruby on rails 查找has_one/BETHING_中不存在关联的模型关联的所有对象
我有两种型号,Ruby on rails 查找has_one/BETHING_中不存在关联的模型关联的所有对象,ruby-on-rails,associations,Ruby On Rails,Associations,我有两种型号,计算机和ipv6地址 Computer belongs_to Ipv6Address Ipv6Address has_one Computer 使用ActiveRecord,我如何找到所有IPV6地址的列表,其中没有与之关联的Computer 及 id是Ipv6Address_id表的主键 ids=Computer.select('Ipv6Address_id') Ipv6Address.select('*').where('id not in (?)',ids) 这可能在使用
计算机
和ipv6地址
Computer belongs_to Ipv6Address
Ipv6Address has_one Computer
使用ActiveRecord,我如何找到所有
IPV6地址的列表,其中没有与之关联的Computer
及
id是Ipv6Address_id表的主键
ids=Computer.select('Ipv6Address_id')
Ipv6Address.select('*').where('id not in (?)',ids)
这可能在使用我的gem时起作用:
Ipv6Address.where('ipv6address_id = ?', nil)
基准测试表明,在大多数情况下,它比将ID数组提取到Ruby并将其发送回数据库要快得多:
# slow
ids = Computer.distinct(:ipv6_address_id).map(&:ipv6_address_id)
Ipv6Address.where.not(id: ids)
能举个例子说明这可能是什么样子吗?我仍在尝试各种选择,还没有找到任何可行的方法。试试我的编辑版本,它可以工作……虽然这不是我需要做的,但这确实让我大部分时间都能做到。我的解决方案:ids=Computer.select('ipv6\u address\u id')。其中('ipv6\u address\u id不为NULL')
# slow
ids = Computer.distinct(:ipv6_address_id).map(&:ipv6_address_id)
Ipv6Address.where.not(id: ids)