Below is my review.html.erb:
<% provide(:title, 'All reviews') %>
<h1>All reviews</h1>
<ol >
<%= render @reviews %>
</ol>
<%= will_paginate @reviews %>
And my _review.html.erb looks like:
<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?
I tried <%= render @reviews, @students %> in review.html.erb and
Student: <%= student.name%>
in _review.html.erb. It didn't work.CodePudding user response:
You don't actually need to pass multiple parameters. You just need to setup the assocations between reviews and users:
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:
@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:
<%= render @reviews, locals: { foo: 'bar' } %>
This will be available in the partial as foo
or local_assigns(:foo)
.
CodePudding user response:
- Reivew table and students are related
In _review.html.erb
, you don't need use Student.find(review.student_id)
<li>
<p>Student: <%= review.student?.name%></p> // changed
....
</li>