Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails render partial with :collection

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

like image 854
32423hjh32423 Avatar asked Dec 14 '12 02:12

32423hjh32423


2 Answers

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

like image 192
Rog Avatar answered Sep 21 '22 03:09

Rog


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.

like image 30
cbascom Avatar answered Sep 22 '22 03:09

cbascom