我很好奇这两个查询是否相同以解决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
答案 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
..