Search code examples
ruby-on-railsnomethoderroractioncontroller

Ruby on rails: undefined method `[]' for nil:NilClass?


when i try to create it says undefined method.

def create
    @stock = Stock.find(params[:stock_availabilities][:stock_id])
    @stock_availability = StockAvailability.new(stock_availabilities_params)
    respond_to do |format|
        if @stock_availability.save 
            format.html { redirect_to stock_path(v_id: @volunteer.id), notice: "stock saved successfully" }  
        else
            @stock_availabilities = StockAvailability.where(stock_id: @stock.id).all
            format.html { render 'index' }
        end
    end
end

Where stock_availabilities belongs to Stock table. foreign key is stock_id.

The params Generated in log is

Parameters: {
    "utf8"=>"✓", 
    "authenticity_token"=>"ZWxRnGJqwLmhfosIhQ+xdLrG3HJXy1m/dHcizT+Y5+E=", 
    "stockavailability"=>{
        "qty"=>"20",
        "price"=>"2000",
        "captured_at"=>"26/8/2015"
        }, 
    "commit"=>"Save Stockavailability"
}
    Completed 404 Not Found in 1ms

Solution

  • I kind of regenerated your issue

    2.1.1 :003 > a=nil
     => nil 
    2.1.1 :004 > a['asd']
    NoMethodError: undefined method `[]' for nil:NilClass
        from (irb):4
        from /home/illu/.rvm/rubies/ruby-2.1.1/bin/irb:11:in `<main>'
    2.1.1 :005 > 
    

    In your case it probably params[:stock_availabilities] is giving nil and you are trying to access the key :stock_id in the nil class. I suggest you to pry the values at the point.

    EDIT1:

    After having a look at your server log it is clear that the key stock_availabilities you are trying to access is actually stockavailability

    your code should be like

    # though no :stock_id key/value is found in your server log
    @stock = Stock.find(params[:stockavailability][:stock_id])