0

所以,让我们说我有一个用户类,和我获取用户的实例,像这样:与查询模型预加载协会

@user = User.first 

而且可以说用户的has_many:帖子,并张贴的has_many:评论。我想预先加载帖子和评论关联以便以后使用。这可以通过执行:ActiveRecord::Associations::Preloader.new.preload(@user, {:posts => :comments}) 但是我也想对这个模型运行一些查询,它是预加载的关联。所以基本上,我想要一些相当于 User.where({:comments => {:post => {:topic => "math"}}).includes({:posts => :comments}).find(some_id)的东西。但是,因为我已经加载了模型一次,我不想再加载它。有没有办法将where子句传递给上述Preloader声明以创建一个大的SQL查询而不是几个较小的查询?我使用的是Postgres,从我的理解来看,通常意味着更少的查询意味着更快的查找时间。

回答

0

使用

@user = User.includes(posts: :comments).first 

那么后续查询将在预装的帖子运行和评论 或使用该查询的缓存版本...

0

我想请你,请指定更多的细节我无法正确理解你想要什么。 不亚于我能够明白我在这里指定用有用的代码请更新相同的,如果这不会是有益的

我有一个模型

应用程序/模型/ user.rb

class User < ApplicationRecord 
    has_many :posts 
    has_many :comments 
end 

应用程序/模型/ post.rb

class Post < ApplicationRecord 
    belongs_to :user 
    has_many :comments 
end 

应用程序/模型/ comment.rb

class Comment < ApplicationRecord 
    belongs_to :post 
    belongs_to :user 
end 

这里我们将得到包含主题的所有帖子都是与用户和评论的数学。 所以我们可以写下面的代码。

User.eager_load(:posts,:comments).where({posts: {topic:"math"} }) 

此结果基于所有创建帖子的主题数学和评论的用户。