[英]How to pass more than one parameters to render in rails?
Below is my review.html.erb:以下是我的评论.html.erb:
<% provide(:title, 'All reviews') %>
<h1>All reviews</h1>
<ol class="reviews">
<%= render @reviews %>
</ol>
<%= will_paginate @reviews %>
And my _review.html.erb looks like:我的 _review.html.erb 看起来像:
<li>
<p>Student: <%= Student.find(review.student_id).name%></p>
<p>Score: <%= review.score%></p>
<p>Review: <%= review.review%></p>
<p>Created at: <%= review.created_at%></p>
</li>
How can I pass @students as well to render for example?例如,我怎样才能通过@students 来渲染?
I tried <%= render @reviews, @students %> in review.html.erb and我在 review.html.erb 中尝试了 <%= render @reviews, @students %> 和
Student: <%= student.name%>学生:<%= student.name%>
You don't actually need to pass multiple parameters.您实际上不需要传递多个参数。 You just need to setup the assocations between reviews and students:
您只需要设置评论和学生之间的关联:
class Student < ApplicationRecord
has_many :reviews
end
class Review < ApplicationRecord
belongs_to :student
# optional but avoids a law of demeter violation
delegate :name, to: :student, prefix: true
end
<li>
<p>Student: <%= review.student_name %></p>
<p>Score: <%= review.score %></p>
<p>Review: <%= review.review %></p>
<p>Created at: <%= review.created_at %></p>
</li>
To avoid a N+1 query issue you should use includes
or eager_load
to load the student with the reviews:为避免 N+1 查询问题,您应该使用
includes
或eager_load
为学生加载评论:
@reviews = Review.includes(:student)
.all
If you do actually want to pass additional arguments when rendering a collection (which isn't needed here) you do it with local assigns:如果您确实想在呈现集合时传递额外的 arguments(此处不需要),您可以使用本地分配来完成:
<%= render @reviews, locals: { foo: 'bar' } %>
This will be available in the partial as foo
or local_assigns(:foo)
.这将在部分中以
foo
或local_assigns(:foo)
的形式提供。
In _review.html.erb
, you don't need use Student.find(review.student_id)
在
_review.html.erb
中,您不需要使用Student.find(review.student_id)
<li>
<p>Student: <%= review.student&.name%></p> // changed
....
</li>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.