Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Start a free Courses trial
to watch this video
You've got a working list of comments for each Post. Since each comment has only two attributes, this works okay. But once you start working with more complicated models, sticking their HTML code straight into their associated model's view may not work so well. We've used partials in previous courses to use the same HTML form code to both create and edit model objects. Let's try using partials here to render the HTML that shows a model.
Let's try using partials to render the HTML that shows a comment.
- Move comment HTML to partial template:
app/views/comments/_comment.html.erb
<div>
<strong><%= comment.name %> says:</strong>
<%= comment.content %>
</div>
- Underscore in name indicates this is a partial.
- Note this code still expects a local variable named
comment
. We'll leave that and set it when we render the partial.
Back in views/posts/show.html.erb
, we can call render
with a partial:
argument to render the partial:
<% @post.comments.each do |comment| %>
<%= render partial: "comments/comment", locals: {comment: comment} %>
<% end %>
-
render
will look in theposts/
by default, so we need to addcomments/
on front of partial name - We leave underscore out of file name in
partial:
argument,.html.erb
is added automatically -
locals:
argument takes a hash with the names and values of local variables to set when rendering partial
There's a simpler way to do the same thing: we can loop through a collection and render a partial for each using render
's collection:
argument:
<%= render partial: "comments/comment", collection: @post.comments, as: :comment %>
-
as:
argument takes symbol with name of local variable to assign
The collection:
argument automatically assigns current member to local variable with same name as the partial, so we can remove as: :comment
:
<%= render partial: "comments/comment", collection: @post.comments %>
And here's the ultimate shortcut... we can pass just @post.comments
to render
.
<%= render @post.comments %>
-
render
realizes you're passing it a collection, so it's as if you're passing it as thecollection:
argument. - Also no need for a
partial:
argument.render
seesComment
objects in the collection, so it looks in theviews/comments
folder for a partial named_comment
.
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up