考虑一个简单的关联......
class Person
has_many :friends
end
class Friend
belongs_to :person
end
Run Code Online (Sandbox Code Playgroud)
让所有在ARel和/或meta_where中没有朋友的人最简洁的方法是什么?
然后是一个has_many:通过版本
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
Run Code Online (Sandbox Code Playgroud)
我真的不想使用counter_cache - 而且我从我读过的内容中看起来并不适用于has_many:通过
我不想拉出所有的person.friends记录并在Ruby中循环它们 - 我希望有一个可以与meta_search gem一起使用的查询/范围
我不介意查询的性能成本
离实际的SQL越远越好......
我需要找到没有孩子或所有孩子都患有疾病(状态 = 1)的父母。
class Parent
has_many :children
end
class Child
enum status: [ :confirmed, :not_confirmed ]
belongs_to :parent
end
Run Code Online (Sandbox Code Playgroud)
我知道第一部分,就是寻找没有孩子的父母。
Parent.joins(:children).where('count(children) = 0')
Run Code Online (Sandbox Code Playgroud)
铁轨回答。