How can I code if I want to avoid n plus one issue?

与世无争的帅哥 提交于 2019-12-24 19:07:52

问题


I have these 3 models

  • Student
  • Gender
  • BloodType
  • Prefecture

Student has these three models such as Gender, BloodType, Prefecture. and each of them belongs to Student.

Association is set up already in each model files.

In this case, how can I code if I want to avoid N + 1 issue?

Is it something like this?

@students = Student.find(:all).includes.includes(:gender, :blood_type, :prefecture)

回答1:


You only need .includes once, and you can get rid of the find(:all) since Rails 3 does not require it.

students = Student.includes(:gender, :blood_type, :prefecture)

Having said that, it looks like these are just look up tables and I'd recommend checking out my gem ClassyEnum as a potential replacement if you are concerned about performance issues.



来源:https://stackoverflow.com/questions/17712893/how-can-i-code-if-i-want-to-avoid-n-plus-one-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!