- n + 1 problem
n + 1 questions:
What is: for example, list a (the primary table) is associated list b (from Table), performs n data once acquired primary table a, since the relationship needs to be performed n times a query from table B, total query the number n + 1. Multiple queries on the table, causing performance problems, this is the n + 1 problem.
Why: The main table query only once, really need one by one to the associated query from a table, n times, causing performance problems.
Solution: (1) lazily: the time with the re-query
(2) rails recommend solutions: includes feeding from the table; joins are inner joins, on the intersection; (preload and includes eager_load and can be pre-loaded)#n+1问题 User.all.each do |user| p user.blogs end #查询user表时,把includes进blogs User.includes(:blogs).each do |user| p user.blogs end #使用joins,会产生重复记录,可以用uniq去除 User.joins(:blogs) 或Blog.joins(:user) #select users.* from users inner joins blogs on users.id=blogs.user_id #select blogs.* from blogs inner joins users ... #另外:使用joins关联多个对象 User.joins(:blogs,:articles) <===> User.joins(:blogs).joins(:articles) #select users.* from users #inner joins blogs on users.id=blogs.user_id #inner joins articles on users.id=articles.user_id