1

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.

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

9 Comments

Thanks. The place I feel very confusing is where "comment" is. We have "comments". But I don't get the rule from "comments" to "comment".
If I have <% render @post.abcs %>, should I always expect "do |abc|" ?
By the way, could you please let me know the link of explanation of this magic? I can't find it?
@user3440433, robots.thoughtbot.com/rendering-collections-in-rails is the link, are you not getting it?
Yes, render @post.abcs would define an abc local in your partial template.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.