在Rails 4.2和骨干网中删除,更新的问题

时间:2015-02-10 04:23:03

标签: ruby-on-rails ruby-on-rails-4.2

我无法解决问题。没有严重的错误。所有工作都可以在其他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,新价格添加。但是当我尝试删除或更新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的问题?因为创造很好。

2 个答案:

答案 0 :(得分:0)

你必须阅读错误,ruby正在告诉你究竟是什么问题:

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

因此,第26行是@price.destroy,因此错误告诉您destroy没有方法nil,即。它告诉你@pricenil,即。它没有被设置。与update相同,只是在nil对象上调用update_attributes

希望你能在这里看到问题,即。您没有在@pricedestroy行动中设置update,也未在show行动中设置。{/ p>

答案 1 :(得分:0)

看起来你没有初始化@price,这就是你收到错误的原因。尝试:

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

您还需要在@priceshow行动中初始化update