Rails 使用 :collection 渲染部分 [英] Rails render partial with :collection
问题描述
这很简单,应该不是问题,但我不明白这里发生了什么.
This is so simple it shouldnt be an issue but I dont understand whats going on here.
我有以下代码
class DashboardController < ApplicationController
def bookings
@bookings = Booking.all
end
end
/views/dashboard/bookings.html.erb
/views/dashboard/bookings.html.erb
<%= render 'booking', :collection => @bookings %>
/views/dashboard/_booking.html.erb
/views/dashboard/_booking.html.erb
<%= booking.booking_time %>
我收到以下错误
undefined method `booking_time' for nil:NilClass
但是,如果我在/views/dashboard/_bookings.html.erb 中执行此操作
However if I do this in /views/dashboard/_bookings.html.erb
<% @bookings.each do |booking| %>
<%= render 'booking', :booking => booking %>
<% end %>
我明白(正确)
2012-12-19 09:00:00 UTC
2012-12-28 03:00:00 UTC
这是怎么回事?我真的很想使用 :collection 定义在这里http://guides.rubyonrails.org/layouts_and_rendering.html
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.
来自 http://guides.rubyonrails.org/layouts_and_rendering.html
在上面来自 OP 的示例中,因为部分被称为 booking
而不是 bookings
,Rails 无法推断要在部分中使用的成员名称,因此需要将其显式传递为 as: :booking
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
这篇关于Rails 使用 :collection 渲染部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!