开发者

ActiveModel cascading validator for object and all of its children

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
  at开发者_开发问答tr_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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜