2017-06-23 177 views
1

我試圖執行更新操作,但我不斷收到錯誤「This specialize already exists」,即使我把名稱完全不同。看起來,如果在「更新」操作中我的嵌套有問題,但我在「創建」操作中使用了相同的條件,但它工作正常。如果這是一個明顯而愚蠢的問題,我是新手,所以原諒我。這裏是我的動作控制器代碼:更新功能無法更新記錄

class SpecializesController < ApplicationController 
    before_action :set_specialize, only: [:show, :edit, :update, :destroy] 

    # GET /specializes 
    def index 
    @specializes = Specialize.all 
    end 

    # GET /specializes/1 
    def show 
    end 

    # GET /specializes/new 
    def new 
    @specialize = Specialize.new 
    end 

    # GET /specializes/1/edit 
    def edit 
    end 

    # POST /specializes 
    def create 
    if(specialize_params[:name].present? && specialize_params[:specialize_category_id].present?) 
     @specialize = Specialize.new(specialize_params) 
     if Specialize.where(:name => @specialize.name).blank? 
     @specialize.save 
     redirect_to specializes_url, notice: 'Specialize was successfully created.' 
     else 
     redirect_to specializes_url, notice: 'This specialize already exists.' 
     end 
    else 
     redirect_to specializes_url, notice: 'One or more input is blank. Add failed!' 
    end 
    end 

    # PATCH/PUT /specializes/1 
    def update 
    if(specialize_params[:name].present? && specialize_params[:specialize_category_id].present?) 
     if Specialize.where(:name => @specialize.name).blank? 
     @specialize.update(specialize_params) 
     redirect_to specializes_url, notice: 'Specialize was successfully updated.' 
     else 
     redirect_to specializes_url, notice: 'This specialize already exists.' 
     end 
    else 
     redirect_to specializes_url, notice: 'One or more input is blank. Update failed!' 
    end 
    end 

    # DELETE /specializes/1 
    def destroy 
    @specialize.destroy 
    redirect_to specializes_url, notice: 'Specialize was successfully destroyed.' 
    end 

    private 
    # Use callbacks to share common setup or constraints between actions. 
    def set_specialize 
     @specialize = Specialize.find(params[:id]) 
    end 

    # Only allow a trusted parameter "white list" through. 
    def specialize_params 
     params.require(:specialize).permit(:name, :specialize_category_id) 
    end 
end 
+0

作爲答案提,你應該這樣的驗證檢查的理想移到模型。請參閱[活動記錄驗證](http://guides.rubyonrails.org/active_record_validations.html) –

回答

1

內,您的更新方法中,從@specialize.name is nil聲明if Specialize.where(:name => @specialize.name).blank?結果是你的代碼總是去別的塊的原因

我建議,如果你不想使用雙爲@ specialize.name,您可以使用驗證規則打開你的模型specialize.rb和下方添加的檢查,以便名稱必須是唯一

validates :name, :presence => { message: 'must be present'}, uniqueness: { case_sensitive: false , message: 'duplicate name, please enter new name'} 
1

你可以做以下的事情調試此:

@specialize.update(specialize_params) 

將返回你可以用它來檢查驗證是通過與否的布爾值。

您也可以做@specilize.errors以查看試圖保存記錄時是否有任何錯誤。