在Rails 4中使用关联中的作用域

时间:2014-08-07 10:31:16

标签: ruby-on-rails activerecord ruby-on-rails-4

道歉,如果我的标题有点不具体,不知道如何在没有示例代码的情况下对这个问题进行短语。

这里是:

模型:

class Profile < ActiveRecord::Base 
   has_one :gallery
end

class Gallery < ActiveRecord::Base
   has_many :images
   scope :processed_images, -> { joins(:images).on('image.image_processing = false')
end

class Image < ActiveRecord::Base
  mount_uploader :image
  store_in_background :image
end

我想通过关联来获取已处理的图像,例如:

profile.gallery.processed_images

编辑:或者

profile.gallery.images.processed

或在sql:

select * from images where image.gallery_id = ? and image.image_processing = false

我可以浏览profile.gallery协会,还是必须执行类似

的操作
Image.where('gallery_id = ? and image_processing = false', gallery_id)

谢谢!

1 个答案:

答案 0 :(得分:2)

解决方案1:

将范围定义更改为

has_many :processed_images, -> { where(image_processing: false) }, class_name: 'Image'

请记住,scope用于过滤当前类,因此在库模型中定义范围将意味着您要过滤库表。

然后只需致电profile.gallery.processed_images

解决方案2:

将图库模型中的范围移动到图像模型

scope :processed, -> { where(image_processing: false) }

然后只需致电profile.gallery.images.processed