问题
I'm trying to learn Rails better by looking at example applications, and while looking at this line of the source of railscasts.com, I noticed it does this:
<div class="episodes">
<%= render @episodes %>
</div>
What exactly is going on here? Why isn't this documented on the render function? Or is it?
回答1:
This is shorthand for
render :partial => "episode", :collection => @episodes
The form above is documented in the Rails API docs under render (ActionController::Base)
. The shorthand form is not documented as far as I can see except in the Rails Guides.
回答2:
This is a handy shortcut for doing
<%= render :partial => "episode", :collection => @episodes %>
which is another way of doing
<% for episode in @episodes do %>
<%= render :partial => "episode", :locals => { :episode => episode }
<% end %>
which is pretty obvious in what it does :)
Hope that makes sense :)
btw it's really surprising I couldn't find the docs for this too.
回答3:
This is a new shortcut:
<%= render @episodes %>
# equivalent to
<%= render :partial => 'episode', :collection => @episodes %>
You can also do shortcuts with single items
<%= render 'comment', comment => @comment %>
# equivalent to
<%= render :partial => 'comment', :locals => {:comment => @comment} %>
来源:https://stackoverflow.com/questions/2567732/what-does-render-collection-do