Now that we have articles and comments working, take a look at the app/views/articles/show.html.erb template. It is getting long and awkward. We can use partials to clean it up.
First, we will make a comment partial to extract showing all the comments for the article. Create the file app/views/comments/_comment.html.erb and put the following into it:
<p><strong>Commenter:</strong><%= comment.commenter %></p><p><strong>Comment:</strong><%= comment.body %></p>
Then you can change app/views/articles/show.html.erb to look like the following:
<p><strong>Title:</strong><%= @article.title %></p><p><strong>Text:</strong><%= @article.text %></p><h2>Comments</h2><%= render @article.comments %>...
This will now render the partial in app/views/comments/_comment.html.erb once for each comment that is in the @article.comments collection. As the render method iterates over the @article.comments collection, it assigns each comment to a local variable named the same as the partial, in this case comment which is then available in the partial for us to show.
Let us also move that new comment section out to its own partial. Again, you create a file app/views/comments/_form.html.erb containing:
<%= form_with(model: [ @article, @article.comments.build ], local: true) do |form| %><p><%= form.label :commenter %><br><%= form.text_field :commenter %></p><p><%= form.label :body %><br><%= form.text_area :body %></p><p><%= form.submit %></p><% end %>
Then you make the app/views/articles/show.html.erb look like the following:
<p> <strong>Title:</strong><%= @article.title %></p><p><strong>Text:</strong><%= @article.text %></p><h2>Comments</h2><%= render @article.comments %><h2>Add a comment:</h2><%= render 'comments/form' %><%= link_to 'Edit', edit_article_path(@article) %> |<%= link_to 'Back', articles_path %>
The second render just defines the partial template we want to render, comments/form. Rails is smart enough to spot the forward slash in that string and realize that you want to render the _form.html.erb file in the app/views/comments directory.
The @article object is available to any partials rendered in the view because we defined it as an instance variable.