【问题标题】:Preloading associations for a model with queries使用查询为模型预加载关联
【发布时间】:2016-09-01 22:12:40
【问题描述】:
所以,假设我有一个 Users 类,我像这样获取 User 的一个实例:
@user = User.first
假设用户 has_many :posts 和 Post has_many :cmets。我想预加载帖子和 cmets 关联以供以后使用。这可以通过这样做来实现:ActiveRecord::Associations::Preloader.new.preload(@user, {:posts => :comments})
但是我也想在这个模型上运行一些查询,它是预加载的关联。所以基本上,我想要的东西相当于
User.where({:comments => {:post => {:topic => "math"}}).includes({:posts => :comments}).find(some_id)。但是,由于我已经加载了一次模型,我不想再次加载它。有没有办法将 where 子句传递给上面的 Preloader 语句,以便创建一个大 SQL 查询而不是几个较小的 SQL 查询?我正在使用 Postgres,据我了解,一般而言,更少的查询意味着更快的查找时间。
【问题讨论】:
标签:
ruby-on-rails
postgresql
activerecord
eager-loading
preloading
【解决方案1】:
使用
@user = User.includes(posts: :comments).first
随后的查询将在预加载的帖子和 cmets 上运行
或使用该查询的缓存版本...
【解决方案2】:
我想请求您提供更多详细信息,因为我无法正确理解您想要什么。
尽我所能理解,我在这里指定有用的代码请更新相同如果这没有帮助
我有模特
app/models/user.rb
class User < ApplicationRecord
has_many :posts
has_many :comments
end
app/models/post.rb
class Post < ApplicationRecord
belongs_to :user
has_many :comments
end
app/models/comment.rb
class Comment < ApplicationRecord
belongs_to :post
belongs_to :user
end
在这里,我们将获得包含用户和 cmets 主题的所有帖子。
所以我们可以写下面的代码。
User.eager_load(:posts,:comments).where({posts: {topic:"math"} })
此结果基于创建具有主题数学和 cmets 的帖子的所有用户。