gpt4 book ai didi

ruby-on-rails - rails : Prevent parent model from being created and surfacing child model validation errors

转载 作者:行者123 更新时间:2023-12-03 23:51:43 24 4
gpt4 key购买 nike

我已经被这个问题困住了一段时间,并且对嵌套模型和验证如何协同工作感到非常困惑。

在下面的代码中,我的目标是如果子模型(内容)的验证失败,则使父模型(图像或视频)的创建失败。目前,父模型被保存而子模型没有被保存,验证错误是闻所未闻的。如果没有验证错误,那么一切都按预期工作。

#Image.rb
has_one :content,
as: :contentable,
inverse_of: :contentable,
dependent: :destroy

#Video.rb
has_one :content,
as: :contentable,
inverse_of: :contentable,
dependent: :destroy

#Content.rb
belongs_to :contentable,
inverse_of: :content,
polymorphic: true

validate :all_good?

def all_good?
errors.add(:base, "Nope!")
return false
end

非常感谢任何线索或见解!

最佳答案

Rails 有一个名为 validates_associated 的特殊验证。确保相关记录有效。如果关联的记录无效,则父记录也将无效,并且关联的错误将添加到其错误列表中。

在 Image 和 Video 类中添加以下内容:

validates_associated :content

现在如果 content关联无效,视频或图像将不会被保存。
video = Video.new
video.content = Content.new
video.save #=> false
video.valid? #=> false
video.errors #=> [:content => "is invalid"]

关于ruby-on-rails - rails : Prevent parent model from being created and surfacing child model validation errors,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39606449/

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