对象及其所有子对象的 ActiveModel 级联验证器

发布于 2024-11-30 07:38:08 字数 725 浏览 0 评论 0原文

我有一个使用 ActiveModel 的类(尽管不是 ActiveRecord)。它表示从远程 Web 服务检索的 JSON 对象。跟踪对象有一个 ReportLayout 对象数组,每个 ReportLayout 对象都有一个插槽数组等。每个模型类都有一些简单的验证器,如“validates_presence_of”等。

如何启动级联验证,从跟踪对象开始,遍历每个级别的每个对象,验证它们,然后验证其子对象数组?该堆栈有 4 层深度,我们很快将再添加两层。

class Track
  include ActiveModel::Validations
  attr_accessor :name, :report_layouts
  validates_presence_of :name
  validates_length_of :name, :minimum => 4, :maximum => 256
....
end

class ReportLayout
  include ActiveModel::Validations
  attr_accessor :name, :slots, :start_date, :end_date
  validates_presence_of :name
  validates_length_of :name, :minimum => 4, :maximum => 256
....
end

class Slot
...
class SlotModule

谢谢你, 拉杰

I have a class that uses ActiveModel (not ActiveRecord though). It represents a JSON object retrieved from a remote webservice. The track object has an array of ReportLayout objects, and each ReportLayout object has an array of slots, etc etc. Each model class has some simple validators like 'validates_presence_of' and the like.

How do I kick off a cascading validation, starting with a track object, that goes through each object at each level, validates them, and then validates their array of children? The stack is 4 levels deep and we will soon be adding two more levels.

class Track
  include ActiveModel::Validations
  attr_accessor :name, :report_layouts
  validates_presence_of :name
  validates_length_of :name, :minimum => 4, :maximum => 256
....
end

class ReportLayout
  include ActiveModel::Validations
  attr_accessor :name, :slots, :start_date, :end_date
  validates_presence_of :name
  validates_length_of :name, :minimum => 4, :maximum => 256
....
end

class Slot
...
class SlotModule

Thank you,
Raj

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

抚你发端 2024-12-07 07:38:08

看一下内置的 ActiveRecord 类:AssociatedValidator

http://api.rubyonrails。 org/classes/ActiveRecord/Validations/AssociatedValidator.html

这个类允许您进行关联/子类验证。您可能需要使用 validates_with 而不是普通的 validates 方法,但它非常适合您所要做的事情。

如果您不需要任何 activerecord 依赖项,您可以将 Validator 类复制到您自己的 Validators 中。

Take a look at the built in ActiveRecord Class: AssociatedValidator

http://api.rubyonrails.org/classes/ActiveRecord/Validations/AssociatedValidator.html

This class allows you to do associated/child class validations. You will probably need to use validates_with rather than the normal validates method, but it works quite well for doing exactly what you are after.

If you dont want any activerecord dependencies, you could just copy the Validator class in into your own Validators.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文