rails render collection partial

在ruby china上发布了一个关于rails render partial的问题!

 

 

<% @paginated_hits.each_with_index do |hit, index| %>
         <%= render :partial => "search/search_item",:locals => {:hit => hit,:index =>index} %>
<% end %>

 我在渲染partial的时候,是再外层做了循环,官方文档中有一种用法专门用来render collection的

  • index.html.erb
< h1 >Products</ h1 >
<%= render :partial => "product" , :collection => @products %>
  • _product.html.erb
< p >Product Name: <%= product.name %> </ p >

注意: 在_product.html.erb中的product.name指的是 :partial => "product", 而不是collection 指向的@products的单数,也可以通过as指定参数

<%=render :partial=> "product", :collection=> @products, :as=> :item%>

则在partial页面中可以直接使用itme

<%= itme.name %>

 

在本地做了一个简单的测试:

在index页面:

<h1>Listing users</h1>

<% @users.each do |user| %>
<%= render :partial => "your", :locals =>{:your => user} %>
<% end %>
<br />

<%= link_to 'New User', new_user_path %>

 _your.html.erb文件中只是简单的输出用户的名字:

 <%= your.name %>

Started GET "/users" for 127.0.0.1 at 2014-03-07 00:20:24 +0800
Processing by UsersController#index as HTML
  [1m[36mUser Load (0.0ms)[0m  [1mSELECT "users".* FROM "users" [0m
  Rendered users/_your.html.erb (0.0ms)
  Rendered users/_your.html.erb (0.0ms)
  Rendered users/_your.html.erb (0.0ms)
  Rendered users/_your.html.erb (0.0ms)
  Rendered users/_your.html.erb (0.0ms)
  Rendered users/_your.html.erb (0.0ms)
  Rendered users/_your.html.erb (0.0ms)
  Rendered users/_your.html.erb (0.0ms)
  Rendered users/_your.html.erb (0.0ms)
  Rendered users/_your.html.erb (0.0ms)
  Rendered users/_your.html.erb (0.0ms)
  Rendered users/_your.html.erb (0.0ms)
  Rendered users/_your.html.erb (0.0ms)
  Rendered users/_your.html.erb (0.0ms)
  Rendered users/_your.html.erb (0.0ms)
  Rendered users/_your.html.erb (0.0ms)
  Rendered users/_your.html.erb (0.0ms)
  Rendered users/index.html.erb within layouts/application (46.9ms)
Completed 200 OK in 62ms (Views: 62.5ms | ActiveRecord: 0.0ms)

 页面渲染用了62.5ms

 

如果在index页面这样写:

<h1>Listing users</h1>

<%= render :partial => "my", :collection => @users %>

<br />

<%= link_to 'New User', new_user_path %>

_my.html.erb文件中:

  <% my.name %>

 

  页面渲染只用了15.6ms

 

速度竟然差了4倍!

 

 

 

 

 

你可能感兴趣的:(rails render collection partial)