首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Rails 4中使用关联中的作用域

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

Stack Overflow用户
提问于 2014-08-07 10:31:15
回答 1查看 63关注 0票数 0

很抱歉,如果我的标题有点不具体,不知道如何在没有示例代码的情况下表达这个问题。

下面是:

型号:

代码语言:javascript
复制
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

我只想通过关联获得处理过的图像,比如:

代码语言:javascript
复制
profile.gallery.processed_images

编辑:或者也许

代码语言:javascript
复制
profile.gallery.images.processed

或者在sql中:

代码语言:javascript
复制
select * from images where image.gallery_id = ? and image.image_processing = false

我可以通过profile.gallery协会吗?或者我必须做一些类似的事情

代码语言:javascript
复制
Image.where('gallery_id = ? and image_processing = false', gallery_id)

谢谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-08-07 10:35:22

解决方案1:

将范围定义更改为

代码语言:javascript
复制
has_many :processed_images, -> { where(image_processing: false) }, class_name: 'Image'

请记住,scope用于筛选当前类,因此在图片库模型中定义作用域将意味着要筛选图库表。

然后打电话给profile.gallery.processed_images

解决方案2:

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

代码语言:javascript
复制
scope :processed, -> { where(image_processing: false) }

然后打电话给profile.gallery.images.processed

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25180200

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档