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
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
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With