想在 Rails 中查找没有关联记录的记录 [英] Want to find records with no associated records in 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屋!