大家好。当我打开/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
如何解决此错误?它为什么会出现?
答案 0 :(得分:2)
您正在使用 simple_form_for
,所以我猜这一行
<%= f.fields_for :prices do |p|%>
应该是
<%= f.simple_fields_for :prices do |p|%>
查看 Git 了解更多信息。
答案 1 :(得分:1)
在_price.html.erb
局部视图中,您正在使用不存在的表单构建器(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 %>
希望这有帮助!