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

rails prevent object creation in before_create callback

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

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

更好的方法:

与其选择回调,不如考虑使用验证 here.Validation 如果条件失败,肯定会阻止对象创建。希望能帮助到你。

  validate :save_object?
  private: 
   def save_object?
     unless condition_satisifed
       errors[:attribute] << "Your validation message here"
       return false
     end
   end

您也可以使用唯一性验证器...事实上,这是一种更好的方法,因为它们适用于这些情况。

回调的另一件事是,如果一切正常,您必须确保它 returns true(或真值),因为如果回调 return s falsenil,它不会被保存(如果你的 if 条件计算为 false 并且在那之后没有别的是 运行,因为你有例如,您的方法将 return nil 导致您的记录无法保存)

The docs and The guide