开发者

Rails, trouble with scopes

开发者 https://www.devze.com 2023-01-26 16:16 出处:网络
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 evaluat开发者_StackOverflowed a count on a related model... like say:

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 evaluat开发者_StackOverflowed 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, self refers to the constant Thing, and not an instance of Thing. The declaration has_many :photos defines a method photos for instances of Thing. Therefore, Thing (the constant) doesn't have a method called photos.

tl;dr Just use a :joins argument since it will only find records that have photos

scope :with_images, :joins => :photos


It should be:

self.photos.count > 0

or if you're using counter cache:

self.photos_count > 0
0

精彩评论

暂无评论...
验证码 换一张
取 消