2015-02-10 56 views
0

我無法捕捉到問題。不要有嚴重的錯誤。所有在其他Rails應用程序中工作正常,具有相同的配置。在Rails 4.2和主幹中刪除,更新的問題

class PricesController < ApplicationController 
    respond_to :json 

    def index 
    @prices = Price.all 

    respond_with @prices 
    end 

    def show 
    respond_with @price 
    end 

    def update 
    @price.update_attributes(price_params) 

    respond_with @price 
    end 

    def create 
    @price = Price.create(price_params) 

    respond_with @price 
    end 

    def destroy 
    @price.destroy 

    respond_with @price 
    end 

    private 

    def price_params 
    params.require(:price).permit(:title, :cost) 
    end 
end 

當POST全部OK,新價格增加。但是當我嘗試刪除或更新catch 500錯誤

Started DELETE "/prices/2" for ::1 at 2015-02-10 07:49:24 +0400 
Processing by PricesController#destroy as JSON 
    Parameters: {"id"=>"2"} 
Completed 500 Internal Server Error in 1ms 

NoMethodError (undefined method `destroy' for nil:NilClass): 
    app/controllers/prices_controller.rb:26:in `destroy' 


Started PUT "/prices/2" for ::1 at 2015-02-10 08:12:23 +0400 
Processing by PricesController#update as JSON 
    Parameters: {"id"=>"2", "title"=>"Price1 update", "cost"=>140, "created_at"=>"2015-02-10T00:04:39.881Z", "updated_at"=>"2015-02-10T00:04:39.881Z", "price"=>{"id"=>"2", "title"=>"Price1 update", "cost"=>140, "created_at"=>"2015-02-10T00:04:39.881Z", "updated_at"=>"2015-02-10T00:04:39.881Z"}} 
Unpermitted parameters: id, created_at, updated_at 
Completed 500 Internal Server Error in 2ms 

NoMethodError (undefined method `update_attributes' for nil:NilClass): 
    app/controllers/prices_controller.rb:14:in `update' 

也許這是jQuery的問題 - ujs?因爲創建很好。

回答

0

它看起來並不像你正在初始化@price,這就是你得到錯誤的原因。嘗試:

def destroy 
    @price = Price.find(params[:id]) 
    @price.destroy 
    ... 
end 

您還需要在您的showupdate行動初始化@price

0

您必須閱讀錯誤,紅寶石恰恰告訴你的問題是什麼:

NoMethodError (undefined method `destroy' for nil:NilClass): 
    app/controllers/prices_controller.rb:26:in `destroy' 

因此,線26 @price.destroy因此錯誤是告訴你,有沒有方法destroynil,即。它告訴你,@pricenil,即。它沒有設置。與update相同,只是在零對象上調用的是update_attributes

希望這就是所有你需要在這裏看到的問題,即。您沒有在您的destroyupdate操作中設置@price,也不在您的show操作中。

+0

謝謝,但它在另一個應用程序工作。在codechool [骨幹解剖學](https://github.com/codeschool-courses/anatomyofbackbone/blob/master/app/controllers/todos_controller.rb)中,他們沒有在控制器中定義變量。 – colmer 2015-02-10 15:17:27

+0

哎喲,你不解我的答案,然後接受別人說的同樣的話。這刺激了人;)你鏈接到**的應用程序**定義變量,看看'before_filter'。 – smathy 2015-02-10 16:32:10