Rails render partial with :collection
Solution 1
This is an old question but just case others are struggling with it
When a partial is called with a pluralized collection, then the individual instances of the partial have access to the member of the collection being rendered via a variable named after the partial.
From http://guides.rubyonrails.org/layouts_and_rendering.html
In the example above from the OP, because the partial was called booking
instead of bookings
, Rails was failing to infer the member name to be used in the partial, hence the need to pass it explicitly as as: :booking
Solution 2
Your call to render is different than what is shown in the guide. Have you tried render :partial => 'booking', :collection => @bookings
?
I believe you should also be able to use the shorter alternative assuming you are in Rails 3 or later: render @bookings
.
Related videos on Youtube
Comments
-
32423hjh32423 over 1 year
This is so simple it shouldnt be an issue but I dont understand whats going on here.
I have the following code
class DashboardController < ApplicationController def bookings @bookings = Booking.all end end
/views/dashboard/bookings.html.erb
<%= render 'booking', :collection => @bookings %>
/views/dashboard/_booking.html.erb
<%= booking.booking_time %>
I get the following error
undefined method `booking_time' for nil:NilClass
However if I do this in /views/dashboard/_bookings.html.erb
<% @bookings.each do |booking| %> <%= render 'booking', :booking => booking %> <% end %>
I get (correct)
2012-12-19 09:00:00 UTC 2012-12-28 03:00:00 UTC
Whats going on here? I really want to use :collection as defined here http://guides.rubyonrails.org/layouts_and_rendering.html
-
32423hjh32423 over 11 yearsThanks. yea I've tried render :partial => 'booking', :collection => @bookings - but its the same
-
cbascom over 11 yearsOdd, does adding :as => :booking to the render call change anything?
-
omnikron almost 11 years
:as => :booking
fixed this for me, I guess it doesn't do any rails magic to infer the singular name from the collection.