删除问题,在 Rails 4.2 和 backbone 中更新

Problems with delete, update in Rails 4.2 and backbone

我无法捕捉到问题。不要有严重错误。使用相同的配置,在其他 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都OK了,新的价格加上。但是当我尝试删除或更新时出现 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的问题?因为创造很好。

你必须阅读错误,ruby 准确地告诉你问题是什么:

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

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

希望这就是您在这里看到问题所需的全部内容,即。您没有在 destroyupdate 操作中设置 @price,也没有在您的 show 操作中设置

您似乎没有在初始化 @price,这就是您收到错误的原因。尝试:

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

您还需要在 showupdate 操作中初始化 @price