gpt4 book ai didi

activemodel - Rails 5 抛出中止 : how do I setup error messages?

转载 作者:行者123 更新时间:2023-12-03 09:36:39 26 4
gpt4 key购买 nike

Rails 引入了这个 throw(:abort)语法,但现在如何获得有意义的销毁错误?

对于验证错误,可以这样做

if not user.save
# => user.errors has information

if not user.destroy
# => user.errors is empty

这是我的模型
class User

before_destroy :destroy_validation,
if: :some_reason

private

def destroy_validation
throw(:abort) if some_condition
end

最佳答案

您可以使用 errors.add为您的类方法。

用户模型:

def destroy_validation
if some_condition
errors.add(:base, "can't be destroyed cause x,y or z")
throw(:abort)
end
end

用户 Controller :
def destroy
if @user.destroy
respond_to do |format|
format.html { redirect_to users_path, notice: ':)' }
format.json { head :no_content }
end
else
respond_to do |format|
format.html { redirect_to users_path, alert: ":( #{@user.errors[:base]}"}
end
end
end

关于activemodel - Rails 5 抛出中止 : how do I setup error messages?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38625276/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com