简体   繁体   中英

How does Rails know which partial name to render when rendering a collection?

I was reading the starting guide of Rails and i got stucked in the section 7.1. I don't understand how the _comment partial they create in the guide can be rendered in the show view only by writing

  <h2>Comments</h2>
  <%= render @article.comments %>

I copy paste the rest of the guide with the code to make you understand the context:

"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 %>

<h2>Add a comment:</h2>
<%= 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 %>

<%= link_to 'Edit', edit_article_path(@article) %> |
<%= link_to 'Back', articles_path %>

"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."

My question is, how ruby know that we want to render that specific partial to format each comments? The parlial name is _comment, but they don't even mention it in the article show. Thank you.

The relationship is has_many :comments which implies a model of type Comment which in turn implies a template partial name of _comment . The template name and the "underscored" version of the model name are what matter in this particular context.

Ruby on Rails infers a lot of things from your definitions and can do a lot of work for you automatically if you follow the conventions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM