[英]Which many_to_many model should I use to make database queries efficient?
Currently in my app I have the following models: 当前,在我的应用中,我具有以下模型:
has_many :training_times
has_many :training_times
belongs_to :dojo
belongs_to :dojo
I want a student to have many training times, and training times to have many students. 我希望一个学生有很多培训时间,而培训时间有很多学生。
Currently in my student controller I have: 目前,在我的学生控制器中,我有:
def show
@student = Student.includes(:senseis).find(params[:id])
@times = TrainingTime.includes(:dojo).order("time ASC")
@times = sort_by_place_and_day(@times)
end
Which I then render as: 然后我将其渲染为:
If the training time is associated to the current student then I want to highlight it as red, so something like: 如果培训时间与当前学生相关,那么我想将其突出显示为红色,因此类似:
<% if time.students.exists?(@student) %>
<td class="orange">...</td>
<% else %
<td class="normal">...</td>
<% end % >
So my question is: will this query the database again each time? 所以我的问题是:每次都会再次查询数据库吗? How do I associate / include the 2 models so that it doesn't?
如何关联/包括2个模型,以免不关联?
For me, the most efficient approach to this issue is through js. 对我而言,解决此问题的最有效方法是通过js。 Use erb/haml to show all the training times available then add a js code that will go through each of the training times related to the student.
使用erb / haml显示所有可用的培训时间,然后添加一个js代码,该代码将经历与该学生有关的每个培训时间。 The js code will just change the class of the td which is what you want.
js代码只会更改您想要的td的类。 So at most, you only get 3 queries, the student, all the training times and the student's training times.
因此,最多只能获得3个查询,即学生,所有培训时间和学生的培训时间。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.