gpt4 book ai didi

ruby-on-rails - rails 阻止在 before_create 回调中创建对象

转载 作者:行者123 更新时间:2023-12-01 07:18:37 25 4
gpt4 key购买 nike

我想检查新记录的一些属性,如果某些条件为真,则阻止创建对象:

before_create :check_if_exists

def check_if_exists
if condition
#logic for not creating the object here
end
end
我也愿意提供更好的解决方案!
我需要这个来防止偶尔重复的 API 调用。

最佳答案

before_create :check_if_exists

def check_if_exists
errors[:base] << "Add your validation message here"
return false if condition_fails
end

更好的方法:

此处不应选择回调,而应考虑使用验证。如果条件失败,验证肯定会阻止对象创建。希望能帮助到你。
  validate :save_object?
private:
def save_object?
unless condition_satisifed
errors[:attribute] << "Your validation message here"
return false
end
end

关于ruby-on-rails - rails 阻止在 before_create 回调中创建对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28041868/

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