Reputation: 63778
Section 7.1 Rendering Partial Collections has us looping through an array of 'comments' that belong to a 'post', and rendering a partial as the result. I can't get my head around this one.
In "views/posts/show.html.erb" we have this code:
<%= render @post.comments %>
Since a @post
has multiple comments, this somehow knows to use the partial in views/comments/_comment.html.erb
. How is this possible? Will Rails singularize "comments" into "comment"?
Even if Rails knows to singularize "comments" into "comment", how does Rails know to look into views/comments/_comment.html.erb
and not views/posts/_comment.html.erb
?
Upvotes: 0
Views: 118
Reputation: 4169
This is part of the magic of Rails. Because you have a comment.rb
model, which probably belongs_to :post
, it knows that @post.comments
is a collection of comments. You can do a lot with it, too. Say you wanted to use a different partial, you could do
# render a bunch of @images with a different partial
<%= render partial: 'images/_preview', collection: @images %>
# render a partial with a different object than assigned (since images are looking for an 'image' variable inside of an _image file)
<%= render 'images/preview', preview: @image %>
So... yeah. The naming conventions are part of what keeps Ruby 'on Rails'.
Upvotes: 2
Reputation: 1054
If you are new to RoR I think that you have a hell of such questions ahead ;) I think that 'render' method does not get any '@post.comments' string to its input, but proxy collection of Comment objects, so there is no singularization (uff) of string happens here. After that it looks at input: "ok, collection of comments, let's look if there any '_comment' partial in views/comments/ path... oh here it is!" ) automagically!
Upvotes: 0