想在 Rails 中查找没有关联记录的记录 [英] Want to find records with no associated records in Rails

查看:27
本文介绍了想在 Rails 中查找没有关联记录的记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑一个简单的关联...

Consider a simple association...

class Person
   has_many :friends
end

class Friend
   belongs_to :person
end

让所有在 ARel 和/或 meta_where 中没有朋友的人最干净的方法是什么?

What is the cleanest way to get all persons that have NO friends in ARel and/or meta_where?

然后是 has_many :through 版本

And then what about a has_many :through version

class Person
   has_many :contacts
   has_many :friends, :through => :contacts, :uniq => true
end

class Friend
   has_many :contacts
   has_many :people, :through => :contacts, :uniq => true
end

class Contact
   belongs_to :friend
   belongs_to :person
end

我真的不想使用 counter_cache - 从我读过的内容来看,它不适用于 has_many :through

I really don't want to use counter_cache - and I from what I've read it doesn't work with has_many :through

我不想拉取所有 person.friends 记录并在 Ruby 中遍历它们 - 我想要一个可以与 meta_search gem 一起使用的查询/范围

I don't want to pull all the person.friends records and loop through them in Ruby - I want to have a query/scope that I can use with the meta_search gem

我不介意查询的性能成本

I don't mind the performance cost of the queries

离实际 SQL 越远越好...

And the farther away from actual SQL the better...

推荐答案

这仍然很接近 SQL,但它应该让每个没有朋友的人在第一种情况下:

This is still pretty close to SQL, but it should get everyone with no friends in the first case:

Person.where('id NOT IN (SELECT DISTINCT(person_id) FROM friends)')

这篇关于想在 Rails 中查找没有关联记录的记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆