微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

ruby-on-rails-3.2 – Rails渲染部分与:集合

这很简单,不应该是一个问题,但我不明白这里发生了什么.

我有以下代码

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 %>

我收到以下错误

undefined method `booking_time' for nil:NilClass

但是,如果我在/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

这里发生了什么?我真的想使用:这里定义的集合
http://guides.rubyonrails.org/layouts_and_rendering.html

解决方法

这是一个老问题,只是其他人正在努力解决问题

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上面的例子中,由于部分被称为预订而不是预订,因此Rails未能推断在部分中使用的成员名称,因此需要明确地传递它:as:

原文地址:https://www.jb51.cc/ruby/266086.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐