我試圖執行更新操作,但我不斷收到錯誤「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
作爲答案提,你應該這樣的驗證檢查的理想移到模型。請參閱[活動記錄驗證](http://guides.rubyonrails.org/active_record_validations.html) –