Search code examples
ruby-on-railsruby-on-rails-5finder

How do I write a Rails finder method to search for my model where the has_many has no particular attribute?


I'm using Rails 5. I have the following model ...

class City < ApplicationRecord
    ...
    has_many :photos, :autosave => true, :dependent => :destroy, :as => :photo, :inverse_of => :photo

I realize that if I want to search for cities with no photos, I can write this finder ...

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

but what if I want to search for cities that have no photos where the photo's extension attribute is "JPG"?


Solution

  • This will give all the cities which don't have JPG or no photos

    City.where.not(id: Photo.select(:city_id).where(extension: 'JPG'))