SettingsController#update中的NoMethodError

时间:2015-09-05 08:32:40

标签: ruby-on-rails

class SettingsController < ApplicationController
  before_action :set_setting, only: [:edit, :update, :destroy]
  authorize_resource class: false

  def edit
  end

  def index
  end

  def update
    respond_to do |format|
      if Setting.first.update!(setting_params)
        format.html { redirect_to settings_path, notice: "Settings Successfully Updated" }
        format.json { render :show, status: :ok, location: settings_path }
      else
        format.html { render :edit }
        format.json { render json: Settings.errors, status: :unprocessable_entity }
      end
    end
  end

  private
    def set_setting
     @setting = Setting.first(params[:id])
    end

    def setting_params
      params.require(:setting).permit(:component_kinds, :client_kinds, :folder_kinds)
    end
end

这里有更多错误信息 - 更新值时出现以下错误:

`NoMethodError (undefined method update!' for nil:NilClass): app/controllers/settings_controller.rb:13:in block in update' app/controllers/settings_controller.rb:12:in `update'

1 个答案:

答案 0 :(得分:1)

这是因为数据库中没有设置。这会导致 $('#newLayer').click(function addNewLayer() { // Second layergroup not added to the map yet var layerGroupNew = new L.LayerGroup(), imageOverlayUrlNew = 'bb.png', // New imageoverlay added to the second layergroup imageOverlayNew = new L.imageOverlay(imageOverlayUrlNew, bounds).addTo(layerGroup2), // New featuregroup added to the second layergroup featureGroupNew = new L.FeatureGroup().addTo(layerGroupNew); }); 为nil,从而导致未定义方法更新的错误消息!对于nil:NilClass 当你尝试调用更新时!在它上面。

您可以考虑切换到the first! method,如果没有找到记录,则会引发ActiveRecord :: RecordNotFound错误。这将为您提供一种在开发中进行故障排除的方法,以及一个很好的404生产。

在尝试更新之前,另一种解决方法可能是check for existence,如下所示:

Setting.first