div_for: NoMethodError
I am trying an ror tutorial and I came across the following line of code:
index.html.erb:
<%= render :partial => @players %>
_player.html.erb:
<% div_for player do %>
<%= player.FNAME %> <%= player.SURNAME %>
<% end %>
players_controller.rb:
def index
@players = Player.all(:order => "FNAME")
respond_to do |format|
format.html
end
end
I want to modify the index.html.erb so that there is no need for a partial but i开发者_JAVA技巧t's not working properly.
Please see code below.
index.html.erb:
<% div_for @players do %>
<%= @player.FNAME %> <%= @player.SURNAME %>
<% end %>
NoMethodError in Players#index
This is a direct translation of your code:
<% @players.each do |player| %>
<% div_for player do %>
<%= player.FNAME %> <%= player.SURNAME %>
<% end %>
<% end %>
The render :partial
given a collection (@players
this case) would walk through the collection one by one and render the partial for you.
But rendering a collection also gives you a counter and spacer template too.
<div>
<% @players.each do |player| %>
<p><%= player.FNAME %></p>
<p><%= player.SURNAME %></p>
<% end %>
</div>
FYI it's a good idea to keep that stuff in the partial.
Basically, div_for will is looking for an id in order to make:
<div id="the_id">
Because you pass an array, and not an object anymore, it's lost.
You should use content_tag for your purpose.
See doc here: http://api.rubyonrails.org/classes/ActionView/Helpers/TagHelper.html#method-i-content_tag
精彩评论