0

I have two models in my Rails app: Listing and ListingPhoto. I want to set some kind of scope on my model that removes Listings that have no nested ListingPhotos. These are being pulled in from an external API, so I have no easy way to control these saving.

Listing looks like this:

class Listing < ActiveRecord::Base

  acts_as_taggable_on :listing_types

  has_many :listing_photos
  accepts_nested_attributes_for :listing_photos, allow_destroy: true

  private

end

ListingPhoto looks like this:

class ListingPhoto < ActiveRecord::Base
  belongs_to :listing
  validates :listing, presence: true
  mount_uploader :photo, PhotoUploader
end

What would I need to add to my Listing model to stop listings with empty photo sets showing up?

gosseti
  • 965
  • 16
  • 40
  • Take a look here: http://stackoverflow.com/questions/9613717/rails-find-record-with-zero-has-many-records-associated on how to add `with_photo` scope. Then in your controller use `Listing.with_photo` in place of `Listing.all` when preparing a list of listings to show. – moonfly Oct 09 '14 at 02:25

1 Answers1

2

you can add static method in Listing model:

def self.with_photos
    includes(:listing_photos).where.not(:listing_photos => {:listing_id => nil})
end

and then just easily call:

Listing.with_photos
Marko Krstic
  • 1,417
  • 1
  • 11
  • 13