0

次のエラーがあります

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

イベントと場所の2つのモデルがあり、2つのイベントを同時に作成しており、イベントには多くの場所があります。経度はattr_accesorの経度と緯度です。隠しフィールドタイプ。

4

3 に答える 3

2

nilであるかparams、より可能性が高いの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

[]4番目の要素はnilであるため、このメソッドを使用することはできません。

結論はparams[:location]nilであり、配列と思われる要素にアクセスしようとすると、メソッドNilClassがないためにメソッドエラーが発生します[]配列にはあります) 。

于 2013-01-01T23:16:11.537 に答える
2

params[:location]である可能性が非常に高いnilです。さらに、ネストされたモデルフォームを使用して、よりクリーンなコードを作成することを検討する必要があります。ネストされたモデルフォームのRailsCastおよびのドキュメントを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 %>
于 2013-01-01T23:54:52.797 に答える
0

コンソールに書き込みます。

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

来るデータはあなたが期待するものではないのではないかと思います(つまり、[:longitude]はハッシュparams [:location]の一部ではありません)。

于 2013-01-01T23:16:58.727 に答える