我有以下错误
undefined method `[]' for nil:NilClass
app/controllers/events_controller.rb:60:in `create'
我不确定nil在这种情况下是什么意思。这里是控制器,第60行箭头是
def create
@event = current_customer.events.build(params[:event])
@location = @event.locations.build(params[:location])
--->@location.longitude = params[:location][:longitude]
@location.latitude = params[:location][:latitude]
respond_to do |format|
if @location.save
if @event.save
format.html { redirect_to @event, notice: 'Event was successfully created.' }
format.json { render json: @event, status: :created, location: @event }
else
format.html { render action: "new" }
format.json { render json: @event.errors, status: :unprocessable_entity }
end
end
end
end
我有两个模型一个事件和一个位置,我在同一时间创建两个事件和事件有许多位置。经度是attr_accesor经度和纬度。隐藏字段类型
params[:location]
很可能是nil
。此外,您应该考虑使用嵌套模型表单来获得更整洁的代码。参考RailsCast on Nested Model Forms和fields_for
的文档。
理论上,你的模型类应该看起来像这样:
class Customer < ActiveRecord::Base
...
has_many :events
accepts_nested_attributes_for :events
...
end
class Event < ActiveRecord::Base
...
has_one :location
accepts_nested_attributes_for :location
...
end
class Location < ActiveRecord::Base
...
belongs_to :event
...
end
你的控制器像这样:
class EventsController < ApplicationController
def new
current_customer.events.build({}, {}) # instantiate 2 empty events
end
def create
current_customer.events.build(params[:event])
if current_customer.save # should save all events and their associated location
...
end
end
end
和你的视图如下:
<%= form_for @customer do |f| %>
...
<%= f.fields_for :events do |e| %>
...
<%= e.fields_for :location, (e.build_location || e.location) do |l| %>
<%= l.hidden_field :longitude %>
<%= l.hidden_field :latitude %>
<% end %>
...
<% end %>
...
<% end %>
params
为nil,或者更可能的是params[:location]
为nil。
想象:
a = [[1,2], [3,4], [5,6], nil, [7,8]]
a[0][0]
=> 1
a[3][0]
undefined method `[]' for nil:NilClass
因为第四个元素是nil,所以我们不能对它使用[]
方法。
结论是params[:location]
是nil,这样当你试图访问你认为是数组的元素时,你会得到一个方法错误,因为NilClass
没有[]
方法(而数组有)
写入您的控制台:
logger.debug params[:location].class
logger.debug params[:location].inspect
我怀疑传入的数据不是你所期望的(即[:longitude]不是哈希参数[:location]的一部分)