0

我无法抓住问题。不要出现严重错误。在其他 Rails 应用程序中一切正常,具有相同的配置。

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 全部确定时,添加新价格。但是当我尝试删除或更新捕获 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 的问题?因为创建很好。

4

2 回答 2

0

您必须阅读错误,ruby 准确地告诉您问题所在:

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

所以,第 26 行是@price.destroy这样的错误告诉你没有方法destroynil即。它告诉你那@pricenil,即。它未设置。update除了它update_attributes在 nil 对象上被调用之外,与它相同。

希望这就是您在这里看到问题所需要的一切,即。你没有@price在你的destroyupdate行动中设置,也不是在你的show行动中。

于 2015-02-10T04:48:50.677 回答
0

它看起来不像您正在初始化@price,这就是您收到错误的原因。尝试:

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

您还需要@price在您的showupdate操作中进行初始化。

于 2015-02-10T04:49:05.730 回答