I’m not sure what I’m doing wrong here but I want to create scope for a model I have, but I want it to evaluated a count on a related model… like say:
class Thing < ActiveRecord::Base
has_many :photos
scope :with_images, self.photo.count > 0
end
class Photo < ActiveRecord::Base
belongs_to :thing
end
I should then have a scope which would work like
Thing.where('some conditions').with_images
I get a NoMethodError on photos, why wouldn’t this be available as a relation? I don’t want to use it as a method.
There are two things going on here. First, you’re trying to call photo, instead of photos.
However, the you’re still going to get an error because at the time of execution,
selfrefers to the constant Thing, and not an instance of Thing. The declarationhas_many :photosdefines a methodphotosfor instances of Thing. Therefore, Thing (the constant) doesn’t have a method called photos.tl;dr Just use a
:joinsargument since it will only find records that have photos