Reputation: 15
In the example given at
http://guides.rubyonrails.org/getting_started.html
I got confused by variable "comment".
The original version is
<h2>Comments</h2>
<% @post.comments.each do |comment| %>
<p>
<strong>Commenter:</strong>
<%= comment.commenter %>
</p>
<p>
<strong>Comment:</strong>
<%= comment.body %>
</p>
<% end %>
In this version, I can understand "comment" is from |comment|
Then, in section 7, this part is changed into
<h2>Comments</h2>
<%= render @post.comments %>
In the app/views/comments/_comment.html.erb the code is
<p>
<strong>Commenter:</strong>
<%= comment.commenter %>
</p>
<p>
<strong>Comment:</strong>
<%= comment.body %>
</p>
Then I got confused. Where is "comment" declared?
Is there a tutorial introducing how variables declared in ruby on rails?
Thank you very much.
Upvotes: 1
Views: 639
Reputation: 198324
This article should clear it up. The core of it is that
<% render @post.comments %>
will do the same thing as
<% @post.comments.each do |comment| %>
<%= render partial: 'comments/comment', locals: { comment: comment } %>
<% end %>
Your variable comment
inside the partial template is declared by render
, triggered by the locals
hash. The article further explains the magic of how you get the latter from the former.
Upvotes: 3