Ruby on rails Rails在includes(:children)上使用作用域

Ruby on rails Rails在includes(:children)上使用作用域,ruby-on-rails,Ruby On Rails,型号 class User has_many :pictures class Picture belongs_to User mount_uploader :picture, UserPictureUploader def self.profile find_by(is_profile: true) end 控制器 User.includes(:pictures).where(... 查看 =user.pictures.profile.picture_url

型号

class User
  has_many :pictures

class Picture 
  belongs_to User
  mount_uploader :picture, UserPictureUploader
  def self.profile
    find_by(is_profile: true)
  end
控制器

User.includes(:pictures).where(...
查看

=user.pictures.profile.picture_url
这会导致以下问题,即每个图片都将被查询(再次)。 如果我们使用
user.pictures.where(profile:true).picture\u url
它将不会进行任何新的sql查询

问题:
我们如何在已经包含的结果上使用作用域?

下面这样做就可以了

class User
  has_many :pictures
  scope :some_name, -> { includes(:pictures).where(your_query_here) }
end
另外,
作用域
仅用于
(换句话说,它们是
类方法
),如果您想在
实例
上使用它,那么您需要定义一个如下所示的实例方法

class User
  has_many :pictures

  def some_name
    self.includes(:pictures).where(your_query_here)
  end
end

经过一点挖掘,我发现了这个问题

看起来您可以在has\u many关系上设置条件,使其本质上成为您正在寻找的范围配置。大概是这样的:

has_many :old_pictures, :class_name => 'Picture', 
         :foreign_key => 'picture_id', -> { where('created_at < ?', Time.now - 7.days) } 
有很多:旧图片,:class\u name=>“图片”,
:foreign_key=>'picture_id',->{where('created_at<?',Time.now-7.days)}

问题是,此查询在rails中不起作用:includes(:pictures)。where(“user\u pictures.is\u profile=true”)@huanson您需要在末尾追加
。引用(:user\u pictures)
user.includes(:pictures)。where(“user\u pictures.is\u profile=true”)。引用(:user\u pictures)
然后只返回具有该标志的图片的用户。但我们只想包括这些。我想这在rails中是不可能的。@huanson你的意思是什么,但我们只想包括那些?我们希望所有用户,包括图片都包括(:pictures)在配置文件图片(profile:true)的位置,所以只需包括1张图片,如果它确实存在,如果你设置了这个,那么使用includes(:old_pictures),它应该加载图片的作用域版本,而不必在使用图片时重新加载。(当然,您所做的查询会有所不同,这是一个示例)