这两个Activerecord查询只是一个数据库查询。试图解决N + 1

时间:2017-06-08 17:30:52

标签: sql ruby-on-rails activerecord

我很好奇这两个查询是否相同以解决N + 1查询。我只想要对正在创建的数据库进行一次查询。如果它们是相同的,为什么? Activerecord如何处理这个问题?发生了什么事?

products = Product.where(user_id: user.id)
products.includes(:restrictions).select do |product|
   !product.restrictions.map(&:state_name).include?("CT")
end

Product.includes(:restrictions).where(user_id: user.id).select do |product|
   product.restrictions.map(&:state_name).include?("CT")
end

Product有许多Restrictions

1 个答案:

答案 0 :(得分:2)

这两个完全相同..你可以查看他们的sql版本来验证

Product.includes(:restrictions).where(user_id: user.id).to_sql

但是第一个写在不同行上的事实将查询db两次.. 仅限第一个

Product.where(user_id: user.id)

第二个includes预加载相关记录

Product.includes(:restrictions).where(user_id: user.id)

这几乎解释了scopes的概念,它可以链接到活动记录集合对象。您可以将查询划分为多个部分,并将它们定义为scope ..