导轨找到相关零的has_many记录记录 [英] Rails find record with zero has_many records associated

查看:116
本文介绍了导轨找到相关零的has_many记录记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这看起来很简单,但我不能让它转起来的谷歌。

如果我有:

 类城市与LT;的ActiveRecord :: Base的
  的has_many:照片
结束

类图片<的ActiveRecord :: Base的
  belongs_to的:城市
结束
 

我想找到一些没有照片的所有城市。我很想能够调用类似...

  City.wh​​ere(photos.empty?)
 

...但是,这并不存在。那么,你怎么做这种类型的查询?


更新: 现在已经找到了答案,原来的问题,我很好奇,你是怎么构建逆?

IE浏览器:如果我想创建这些作为的范围:

 范围:without_photos,包括(:照片)。凡(:照片=> {:city_id =>无})
适用范围:with_photos,???
 

解决方案

呸,发现在这里: http://stackoverflow.com /一/四十一万七千八百七十二分之五百五十七万○二百二十一

  City.includes(:照片)。凡(照片:{city_id:无})
 

This seems fairly simple but I can't get it to turn up on Google.

If I have:

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: if I wanted to create these as scopes:

scope :without_photos, includes(:photos).where( :photos => {:city_id=>nil} )
scope :with_photos, ???

解决方案

Bah, found it here: http://stackoverflow.com/a/5570221/417872

City.includes(:photos).where(photos: { city_id: nil })

这篇关于导轨找到相关零的has_many记录记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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