Ruby on Rails partial 中使用collection 参数
Here is one my brother showed me the other day that I was not aware of. More RTFM and less Cowboy Coding.. I know, I know.. its just my nature. So here is the use case: You have a collection of objects that you want rendered in a partial. The way I used to do it is like this:
1 #controller code 2 @widgets = Widget.all 3 4 # view code 5 <%= render :partial=>"widgets/widget" %> 6 7 #partial code 8 <% @widgets.each do |widget| %> 9 This widget is named <%=widget.name %> 10 11 <% end %>
Now that is kinda ugly doing the iteration in the partial like that. Now for a cleaner way. You pass the @widgets to the partial with the :collection hash.
1 #controller code 2 @widgets = Widget.all 3 4 # view code 5 <%= render :partial=>"widgets/widget", :collection=>@widgets %> 6 7 #partial code 8 This widget is named <%=widget.name %>
This code will execute the partial multiple times.. once for each widget in the widget collection. That looks damn pretty. One caveat, though.. In the partial, the name of the local variable needs to be the same as the name of the partial. So if you have widgets/some_widget, the code would look like this:
1 This widget is named <%=some_widget.name %>
If you want to use another variable name you just add the :as hash, like this:
1 <%= render :partial=>"widgets/some_widget", :collection=>@widgets, :as=>:widget %>
Then you can use widget as the local variable name instead of some_widget. Got it? Good.