gpt4 book ai didi

ruby-on-rails - rails : How to know in advance if "save" is going to fail?

转载 作者:行者123 更新时间:2023-12-03 18:20:33 27 4
gpt4 key购买 nike

考虑我的 Controller 的这段代码:

def create
change_some_db_values
buyer = Buyer.new(params[:buyer])
if buyer.save
redirect_to(:action => 'index')
else
render('new')
end
end

如果 buyer.save我想提前知道会不会失败。如果它会失败,我不想执行 change_some_db_values .我怎么能做到这一点?

最佳答案

您可以 add a check for validity before saving :

def create
buyer = Buyer.new(params[:buyer])
if buyer.valid?
change_some_db_values
end
if buyer.save
redirect_to(:action => 'index')
else
render('new')
end
end

关于ruby-on-rails - rails : How to know in advance if "save" is going to fail?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4699416/

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