Rails Nil不理解错误

时间:2013-01-01 23:09:51

标签: ruby-on-rails ruby ruby-on-rails-3

我有以下错误

undefined method `[]' for nil:NilClass
app/controllers/events_controller.rb:60:in `create'

在这种情况下,我不确定他们的意思是什么。这里我的控制器和第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经度和纬度。隐藏字段类型。

3 个答案:

答案 0 :(得分:2)

params为零,或者params[:location]更有可能为零。

想象:

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]为零,因此当您尝试访问您认为是数组的元素时,会出现方法错误,因为NilClass没有[]方法(而Array does

答案 1 :(得分:2)

params[:location]很可能是nil。此外,您应该考虑使用嵌套模型表单来获得更清晰的代码。请参阅RailsCast on Nested Model Formsdocs for 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 %>

答案 2 :(得分:0)

写入您的控制台:

logger.debug params[:location].class
logger.debug params[:location].inspect

我怀疑数据的输出并不是你所期望的那样(即[:经度]不是哈希参数[:location]的一部分)。