1

大家好。当我打开/courses/new(或/courses/some_id/edit)时,浏览器返回此错误:

Showing /app/views/dashboard/courses/_price.html.erb where line #1 raised:
undefined method `label' for nil:NilClass

这里是代码,_form.html.erb

 <%= simple_form_for [:dashboard, @course], html: { multipart: true } do |f| %>

//////
<%= f.fields_for :prices do |p|%>
  <%= render 'price', :f => 'prices' %>
<% end %>
<%= link_to_add_association 'Add', f, :prices %>

////////

_price.html.erb

<%= p.label :price %>
<%= p.text_field :price %>
<%= p.label :desc %>
<%= p.text_field :description %>
<%= link_to_remove_association "remove", f %>

楷模:

class Price < ActiveRecord::Base
  belongs_to :course
end
class Course < ActiveRecord::Base
 has_many :prices
 accepts_nested_attributes_for :prices, :reject_if => :all_blank, :allow_destroy => true
end

如何解决这个错误?为什么会出现?

4

2 回答 2

2

你正在使用simple_form_for,所以我猜这条线

<%= f.fields_for :prices do |p|%>

应该

<%= f.simple_fields_for :prices do |p|%>

查看Git了解更多信息。

于 2014-06-18T16:36:33.043 回答
1

在您的_price.html.erb部分视图中,您正在使用一个不存在的表单构建器 (is nil),因为您没有将它作为参数传递:

# _price.html.erb
<%= p.label :price %>
   #^ the variable `p` is the form builder here

要解决此问题,您必须将表单构建器传递给局部视图,如下所示:

<%= f.fields_for :prices do |p| %>
  <%= render 'price', :f => 'prices', p: p %>
                                     #^^^^ We pass the variable `p` (form builder) to the partial
<% end %>

希望这可以帮助!

于 2014-06-18T16:41:57.607 回答