简体   繁体   中英

Unsure about using partials in Rails

So I'm doing the railstutorial by Michael Hartl and am on Chapter 9. This bit of code is for pagination where render user renders a partial (named _user) with embedded ruby for the profile picture and user name

<% provide(:title, 'All users') %>
<h1>All users</h1>

<%= will_paginate %>

<ul class="users">
  <% @users.each do |user| %>
  <%= render user %>
  <% end %>
</ul>

<%= will_paginate %>

However this code is refactored into

<% provide(:title, 'All users') %>
<h1>All users</h1>

<%= will_paginate %>

<ul class="users">
  <%= render @users %>
</ul>

<%= will_paginate %>

My question now is how does Rails know to render the partial _user since there are no explicit instructions to do so? I've tried changing the name of the partial to figure out how, but I still don't know. For example I renamed the partial _users and it caused an error. Thanks for the help.

It knows that the @users collection that you made is made up of instances of the class User , so when you call render @users in a view, it looks for a file called _user.html.erb and renders that file end to end for every User instance in the collection. Within the partial, you can access the iteration of the partial's corresponding User instance with user .

If you had a collection called @my_collection and it was made up of instances of the class Howdy , then render @my_collection would look for a partial named _howdy.html.erb and render it for every Howdy instance in @my_collection . The iteration of the partial's corresponding Howdy instance would be accessible as howdy within the partial.

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