2015-09-05 38 views
-4
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在SettingsController#更新

`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

請給我們完整的跟蹤 – dimakura

+1

歡迎堆棧溢出!你給我們發佈了一些代碼是很好的,但是解釋問題是什麼以及你想要什麼幫助可以幫助我們。使用[編輯]按鈕添加一些文字,可以幫助我們解釋您的問題。 –

回答

1

這正在造成的。這導致Setting.first爲零,這反過來導致您的錯誤消息未定義的方法更新! for nil:NilClass當您嘗試致電更新!在上面。

您可能會考慮切換到the first! method,如果未找到任何記錄,將會引發ActiveRecord :: RecordNotFound錯誤。這將爲您提供開發過程中的故障排除方法,以及生產中的好404。

另一種方式來解決它可能是check for existence試圖更新,像這樣前:

if Setting.exist? && Setting.first.update!(setting_params)

+0

我有數據庫中的設置。 create_table「settings」,force::cascade do | t | t.string 「settable_type」 t.integer 「settable_id」 t.hstore 「settables」 t.integer 「CREATED_BY」 t.integer 「updated_by」 t.datetime 「created_at」,空:假 t.datetime 「updated_at」,null:false 結束 – geethujoseph

+0

我對此表示懷疑。嘗試在控制檯中運行'Setting.first'。我敢打賭它是零。或者,像我推薦的那樣調整方法,並且您將收到記錄未找到的錯誤。 –

+0

設置表中的條目,而不是表格本身。首先檢索第一個條目。 –