我正在尝试执行更新操作,但我不断收到错误“此专门化已经存在”,即使我把名称完全不同。看来我的嵌套if在Update操作中有问题,但我在Create操作中使用了相同的条件,但它工作正常。如果这是一个明显而愚蠢的问题,我是新手,请原谅我。这是我的动作控制器代码:
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 :(得分:1)
您可以执行以下操作来调试此操作:
@specialize.update(specialize_params)
将返回一个布尔值,您可以使用该值来检查验证是否正在通过。
您还可以@specilize.errors
查看尝试保存记录时是否有任何错误。
答案 1 :(得分:1)
在更新方法中,来自语句@specialize.name is nil
的{{1}}的结果是您的代码始终转到else块的原因
我建议如果你不想为@ specialize.name使用double,你可以使用验证规则打开你的模型specialize.rb并在下面添加是检查所以name必须是唯一的
if Specialize.where(:name => @specialize.name).blank?