对象及其所有子对象的 ActiveModel 级联验证器
我有一个使用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
看一下内置的 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.