Rails 查找具有零个 has_many 记录的记录 [英] Rails find record with zero has_many records associated
本文介绍了Rails 查找具有零个 has_many 记录的记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这看起来很简单,但我无法在 Google 上显示.
This seems fairly simple but I can't get it to turn up on Google.
如果我有:
class City < ActiveRecord::Base
has_many :photos
end
class Photo < ActiveRecord::Base
belongs_to :city
end
我想找到所有没有照片的城市.我希望能够调用类似...
I want to find all cities that have no photos. I'd love to be able to call something like...
City.where( photos.empty? )
...但这并不存在.那么,您如何进行此类查询?
...but that doesn't exist. So, how do you do this kind of query?
更新:现在找到了原始问题的答案,我很好奇,你如何构造逆?
Update: Having now found an answer to the original question, I'm curious, how do you construct the inverse?
IE:如果我想将这些创建为范围:
IE: if I wanted to create these as scopes:
scope :without_photos, includes(:photos).where( :photos => {:city_id=>nil} )
scope :with_photos, ???
推荐答案
呸,在这里找到:https://stackoverflow.com/a/5570221/417872
City.includes(:photos).where(photos: { city_id: nil })
这篇关于Rails 查找具有零个 has_many 记录的记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文